如何从GUI写入struct

时间:2016-07-12 16:54:22

标签: qt user-interface struct qdial

使用Qt,我试图通过gui的输入写入我的结构。

我的target.h文件:

struct Target{
    double heading;
    double speed;
};

我的cpp:

#include <target.h>

struct Target myship;

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

我使用QDial作为标题作为示例。我可以将QDial的值写入文本文件,但我想利用结构。

我想知道的是如何访问,以便我可以写入mainwindow.cpp中的结构?

我看到我可以在mainwindow.cpp中访问我的Target结构,如下所示:

Target.heading

但它不会找到“神秘”。我本以为我可以做到

myship.heading...

Target.myship.heading...

但两者都没有效果。当我做Target.heading它给我错误

expected unqualified-id before '.' token

我的最终目标是让我的gui(在这种情况下为QDial)写入结构,然后让我的gui(QLabel)显示已写入的内容。如前所述,我使用文本文件进行读/写操作,但我目前只写出一个值,这不符合我的要求。

我是Qt的新手和一般的结构,所以我的猜测是我错过了一些非常微不足道的东西,或者我的理解完全消失了。

1 个答案:

答案 0 :(得分:2)

您在struct变量定义中使用的myship前缀是C-ism。它不属于C ++。您应该将myship定义为:

Target myship;

此外,自2016年以来,你应该使用C ++ 11所拥有的一切来让你的生活更轻松。非静态/非const类/结构成员的初始化非常有用,并且避免了结构体使用时的样板。因此,更喜欢:

// 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;
}

请注意,您应将自己的标题添加为#include "header.h",而不是#include <header.h>。后者保留给系统头。

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;
}