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; workerObject.moveToThread(&workerThread); workerThread.start(); MyMainWindow window(workerObject); // create connections UI <-> workerObject in the constructor window.show(); return a.exec(); }
Or should i create the QThread and my WorkerObject in the MyMainWindow class?
Thanks!
-
@beecksche
It's quite fine, but you should create the worker object in the heap and connect the thread'sfinished
signal to the worker object'sdeleteLater
slot. Wherever you create the actualQThread
instance and the worker object is of no consequence, as all the widgets are running on top of themain()
stack frame (in the same thread) anyway.PS.
Also, if I were you I'd connect theaboutToQuit
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; workerThread.start(); workerObject->moveToThread(&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.