Qt moc 在头文件中实现?

2021-12-09 00:00:00 qt c++ moc

是否可以告诉 Qt MOC 我想声明该类并在单个文件中实现它,而不是将它们拆分为 .h 和 .cpp 文件?

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?

推荐答案

我相信这是最好的方法.这实际上是我现在构建所有对象的方式.

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 <QtGui>
#include "Window.h"

int main(int argc, char *argv[])
{
    QApplication app(argc,argv);

    Window window;
    window.show();
    return app.exec();
}

窗口.h

#ifndef WINDOW_H
#define WINDOW_H

#include <QtGui>
#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 <QtGui>

class MyWidget : public QLabel
{
    Q_OBJECT

public:
    MyWidget(QString text) : QLabel(text)
    {
        // Whatever
    }
};

#include "moc_MyWidget.cpp"

#endif // MYWIDGET_H

构建...qmake Works.pro

Build... qmake Works.pro

制作

相关文章