QTimer timeout signal does not trigger a slot when starting in another thread

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.

+4
source share
1 answer

I solved my problem !! In the MyObject constructor, the timer is allocated on the heap as follows:

 timer_ptr = new QTimer(this); 

but for it to work it should be:

 timer_ptr = new QTimer(0); 

and in the destructor, delete the object manually:

 timer_ptr->deleteLater(); 

I think when they say that they cannot move the object with the parent to the stream, they really mean ALL objects, including the data elements of the object that are actually moving to the new stream.

Happy coding.

+3
source

Source: https://habr.com/ru/post/1443887/


All Articles