[英]How to write to struct from a GUI
使用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”。 我本以為可以做到
myship.heading...
要么
Target.myship.heading...
但是都沒有用。 當我執行Target.heading時,它給了我錯誤
expected unqualified-id before '.' token
我的最終目標是讓我的gui(在這種情況下為QDial)寫入該結構,然后讓我的gui(QLabel)顯示所編寫的內容。 如前所述,我可以對文本文件進行讀/寫操作,但是我目前僅寫出一個值,無法滿足我的要求。
我是Qt和struct的新手,所以我的猜測是我缺少一些瑣碎的東西,或者我的理解完全不對。
在myship
變量的定義中使用的struct
前綴是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>
。 后者是為系統頭保留的。
沒有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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.