I have a QObject subclass called myObject that has a QTimer data member allocated on the heap in the constructor. myObject also has a slot that is connected to the QTimer () timeout signal in the constructor. I refer to myObject pointer as myObject_ptr.
I want to run myObject in another thread from the main thread. Following relatively new guidelines, I DO NOT subclass QThread. In the main thread, I use myObject as follows:
QThread *thread = new QThread(this); myObject_ptr->moveToThread(thread); connect(myObject_ptr, SIGNAL(destroyed(), thread, SLOT(quit())); //thread not needed if no object connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); //to avoid memory leak connect(thread, SIGNAL(terminated()), thread, SLOT(deleteLater())); //to avoid memory leak thread->start();
The main thread calls the myObject_ptr function, which in turn runs the QTimer data item. When the time runs out, nothing happens, but I expect that the myObject slot to which the timer () timeout signal is connected will be called. What is the problem? How do you do this job. It works flawlessly if myObject runs in the same thread where it was created, i.e. Main stream.
From all the readings I have made, I think that the new thread that I create may not handle events because it does not have its own event loop. I also read documentation / articles that contradict this, saying that when the thread starts, the run () function calls exec () and you have an event loop.
Can anyone help me?
I could make it work correctly if I subclassed QThread, but based on current recommendations, I would prefer not to.
Thanks in advance.
source share