2009-11-01 54 views
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(); 

回答

5

你不应该使用不同的名字?

QDialog *hWorld = new hWorld; 

是相当混乱,你会得到,使用HWorld为类,而不是(例如)错误的来源,因为它是通用启动类型名称以大写字母(上camel大小写)。

另外,故意将QWidget更改为QDialog

+0

谢谢。 是的,我确实把它改成QDialog,但我用各种示例代码拼凑了代码。我已经做出了您所建议的更改,并且现在可以运行。 – 2009-11-02 09:03:28

+1

这么认为,无论如何,这两者实际上都适用于您的示例。 Qt有趣,它是一个非常强大和方便的框架! :-) – RedGlyph 2009-11-02 09:43:07