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 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();