views:

343

answers:

2

Sometimes you need to create a very simple single file application in Qt4. However it's problematic since you are always doing the CPP/H separation, and then the main() is in another file...

Any ideas how to do this in a single file? As quick as dirty as possible.

+1  A: 

If you need to build a quick prototype, using Python and PyQt4 is even more compact:

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_())

No need to call qmake or to bother with .moc files.

Aaron Digulla
I use it many times to send bugs to Trolltech/QtSoftware/Nokia. I am not sure PyQt4 is the best way of doing it.
elcuco
As I said: "If you need to build a quick prototype". Keep in mind that other people might have slightly different needs.
Aaron Digulla
+2  A: 

This is an example that shows how to do this in a single file. Just throw this in a new directory, save it as "main.cpp" and then run qmake -project; qmake; make to compile.

#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"

Two tricks in this demo:

  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.
elcuco