0
我剛開始使用Qt。儘管今天晚上花了一些時間,但我努力將我的UI設置代碼從main
移到它自己的類中。將Qt UI代碼移出到單獨的類中
#include <QtGui>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QWidget *window = new QWidget;
QLabel *hw = new QLabel(QObject::tr("Hello World!"));
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(hw);
window->setLayout(layout);
window->show();
return app.exec();
}
我試着做我自己的類並傳遞給window
,但碰上編譯錯誤。
main.cpp中:
#include <QtGui>
#include "hworld.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QDialog *hWorld = new hWorld;
hWorld->show();
return app.exec();
}
hworld.h:
#ifndef HWORLD_H
#define HWORLD_H
#include <QtGui>
class hWorld : public QDialog {
Q_OBJECT
public:
hWorld(QWidget *parent = 0);
~hWorld();
private:
void setup();
};
#endif // HWORLD_H
hworld.cpp:
#include <QtGui>
#include "hworld.h"
hWorld :: hWorld(QWidget *parent) : QDialog(parent) {
setup();
}
hWorld :: ~hWorld() { }
void hWorld :: setup() {
QLabel *hw = new QLabel(QObject::tr("Hello World!"));
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(hw);
setLayout(layout);
setWindowTitle("Test App");
}
編譯錯誤:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:8: error: expected type-specifier before ‘hWorld’
main.cpp:8: error: cannot convert ‘int*’ to ‘QDialog*’ in initialization
main.cpp:8: error: expected ‘,’ or ‘;’ before ‘hWorld’
make: *** [main.o] Error 1
改變main
,意味着這個編譯,但我得到了一個空白窗口(因爲構造不叫):爲類和實例變量
QDialog hWorld;
hWorld.show();
謝謝。 是的,我確實把它改成QDialog,但我用各種示例代碼拼湊了代碼。我已經做出了您所建議的更改,並且現在可以運行。 – 2009-11-02 09:03:28
這麼認爲,無論如何,這兩者實際上都適用於您的示例。 Qt有趣,它是一個非常強大和方便的框架! :-) – RedGlyph 2009-11-02 09:43:07