2

有时您需要在 Qt4中创建一个非常简单的单文件应用程序。然而这是有问题的,因为你总是在做 CPP/H 分离,然后 main() 在另一个文件中......

任何想法如何在单个文件中执行此操作?尽可能快地弄脏。

4

2 回答 2

2

这是一个示例,展示了如何在单个文件中执行此操作。只需将其扔到一个新目录中,将其保存为“main.cpp”,然后运行qmake -project; qmake; make编译即可。

#include <QtGui/QApplication>
#include <QtGui/QMainWindow>
#include <QtGui/QPushButton>

class MainWindow : public QMainWindow {
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0){
        button = new QPushButton("Hello, world!", this);
    }
private:
    QPushButton *button;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

#include "main.moc"

此演示中有两个技巧:

  1. First is how to call "qmake -project" to create a *.pro file with the files in the current directory automagically. The target name by default is the name of the directory, so choose it wisely.
  2. Second is to #include *.moc in the CPP file, to ask moc to preprocess the CPP files for QObject definitions.
于 2009-09-01T10:29:14.237 回答
1

如果需要快速构建原型,使用 Python 和PyQt4会更加紧凑:

import sys
from PyQt4.QtGui import *

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.button = QPushButton("Hello, world!", self)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

无需打电话qmake或打扰.moc文件。

于 2009-09-01T10:13:40.337 回答