Qt moc with implementations inside of header files?

前端 未结 4 2014
鱼传尺愫
鱼传尺愫 2020-11-30 11:27

Is it possible to tell the Qt MOC that I would like to declare the class and implement it in a single file rather than splitting them up into an .h and .cpp file?

4条回答
  •  暖寄归人
    2020-11-30 12:00

    I believe this to be the best way. It's actually how I construct all of my objects now.

    Qt 4.8.7

    Works.pro:

    SOURCES += \
        main.cpp
    
    HEADERS += \
        Window.h \
        MyWidget.h
    

    main.cpp

    #include 
    #include "Window.h"
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc,argv);
    
        Window window;
        window.show();
        return app.exec();
    }
    

    Window.h

    #ifndef WINDOW_H
    #define WINDOW_H
    
    #include 
    #include "MyWidget.h"
    
    class Window : public QWidget
    {
        Q_OBJECT
    
    private:
        MyWidget *whatever;
    
    public:
        Window()
        {
            QHBoxLayout *layout = new QHBoxLayout;
            setLayout(layout);
    
            whatever = new MyWidget("Screw You");
            layout->addWidget(whatever);
    
        }
    };
    
    #include "moc_Window.cpp"
    
    #endif // WINDOW_H
    

    MyWidget.h

    #ifndef MYWIDGET_H
    #define MYWIDGET_H
    
    #include 
    
    class MyWidget : public QLabel
    {
        Q_OBJECT
    
    public:
        MyWidget(QString text) : QLabel(text)
        {
            // Whatever
        }
    };
    
    #include "moc_MyWidget.cpp"
    
    #endif // MYWIDGET_H
    

    Build... qmake Works.pro

    make

提交回复
热议问题