Moving Qt UI code out to separate class
I'm just starting with Qt. Despite spending sometime on it this evening, I'm struggling to move my UI setup code out of main
into it's own class.
#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();
}
I've tried making my own class and passing开发者_StackOverflow中文版 window
to it but run into compilation errors.
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");
}
Compilation errors:
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
Changing main
, means this compiles but I get a blank window (because the constructors not called?):
QDialog hWorld;
hWorld.show();
Shouldn't you use a different name for the class and the instantiated variable?
QDialog *hWorld = new hWorld;
is quite confusing and the source of the error you get, use HWorld
for the class instead (for example), since it is common use to start a type name with an upper case (upper camel casing).
Also, is the change from QWidget
to QDialog
on purpose?
精彩评论