tags:

views:

318

answers:

1

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();
+4  A: 

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?

RedGlyph
Thanks.Yes I did change it to QDialog but I cobbled the code together from various example code. I've made the changes you suggested and it runs now.
Greg K
Thought so, and both actually work in your example anyway. Have fun with Qt, it's a very powerful and convenient framework! :-)
RedGlyph