简体   繁体   中英

How to write to struct from a GUI

Using Qt, I'm trying to write to my struct via inputs from a gui.

my target.h file:

struct Target{
    double heading;
    double speed;
};

my cpp:

#include <target.h>

struct Target myship;

myship.heading = 0;
myship.speed = 0;

I am using a QDial for the heading as an example. I can write the value of the QDial to a text file, but I would like to take advantage of structs.

What I'd like to know is how do I access, so that I can write to, the struct in my mainwindow.cpp?

I see that I can access my Target structure in mainwindow.cpp like this:

Target.heading

But it won't find "myship". I would have thought that I could have done

myship.heading...

or

Target.myship.heading...

But neither is working. When I do Target.heading it gives me the error

expected unqualified-id before '.' token

My ultimate goal is to have my gui (QDial in this case) write to the struct, and then have my gui (QLabel) display what has been written. As mentioned before, I have the read/write working with a text file, but I'm currently only writing out a single value, which isn't going to meet my requirements.

I'm new to Qt and structs in general so my guess is I'm missing something pretty trivial, or my understanding is off completely.

The struct prefix that you've used in the definition of the myship variable is a C-ism. It doesn't belong in C++. You should define myship as:

Target myship;

Furthermore, since it's 2016, you should use everything C++11 has got to make your life easier. Initialization of non-static/non-const class/struct members is very helpful and avoids boilerplate at the point of use of the struct. Thus, prefer:

// target.h
#include <QtCore>
struct Target {
  double heading = 0.0;
  double speed = 0.0;
};
QDebug operator(QDebug dbg, const Target & target);

// target.cpp
#include "target.h"
QDebug operator(QDebug dbg, const Target & target) {
  return dbg << target.heading << target.speed;
}

// main.cpp
#include "target.h"
#include <QtCore>

int main() {
  Target ship;
  qDebug() << ship;
}

Note that you should include your own headers as #include "header.h" , not #include <header.h> . The latter is reserved for system headers.

Without Qt :

#include <iostream>
struct Target {
  double heading = 0.0;
  double speed = 0.0;
};

int main() {
  Target ship;
  std::cout << ship.heading << " " << ship.speed << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM