Important: Please read the Qt Code of Conduct -

QThread in main-function

  • Hi,
    i am not quite sure if it is allowed to create a QThread in the main/entry-function.
    My code looks like the following schema, all works fine, but i'm not sure if it's just coincidence.

    #include <QtWidgets/QApplication>
    #include <QThread>
    int main(int argc, char *argv[])
    	QApplication a(argc, argv);
    	MyObject workerObject; // inherits from QObject
    	QThread workerThread;
    	MyMainWindow window(workerObject);  // create connections UI <-> workerObject in the constructor;
    	return a.exec();

    Or should i create the QThread and my WorkerObject in the MyMainWindow class?


  • Moderators

    It's quite fine, but you should create the worker object in the heap and connect the thread's finished signal to the worker object's deleteLater slot. Wherever you create the actual QThread instance and the worker object is of no consequence, as all the widgets are running on top of the main() stack frame (in the same thread) anyway.

    Also, if I were you I'd connect the aboutToQuit signal from the application object to post the quit event and wait for the thread to finish. Something along the lines:

    int main (int argc, char ** argv)
        QApplication app(argc, argv);
        MyObject * workerObject = new MyObject;
        QThread workerThread;
        QObject::connect(&workerThread, SIGNAL(finished()), workerObject, SLOT(deleteLater()));
        QObject::connect(&app, SIGNAL(aboutToQuit()), &workerThread, SLOT(quit()));
        // ...
        int status = QApplication::exec();
        workerThread.wait(5000); // Wait up to 5 seconds for the worker to wrap things up, if it doesn't, just exit
        return status;

    There are better and more sophisticated ways to wait for the worker, but this is simple and effective enough.

    Kind regards.

  • Thanks for your reply and help!

Log in to reply