MoveToThread and QTimer
-
Hi, I've not checked directly, but the timer is not a child of MyObject2 thus is not moved to the new thread.
-
m_timer is not parented to anything, thus it is not moved to the thread.
-
Be aware that just because m_timer is a member of a QObject-based class, it does not automatically become a child of it and thus, as luca already pointed out, it is not moved to the new thread.
You either move it explicitly or set the surrouding class as the parent to get it moved implicitly.
-
Thanks luca, you've answered about our question above but I didn't read it. Sorry.
I tried:
- Add new member variables to MyObject2 (QTimer* m_timer2, m_timer3).
- Add this code under line 55 (MyObject2::process()).
@m_timer2 = new QTimer();
m_timer3 = new QTimer(this);
qDebug() << "Parent of m_timer is" << m_timer.parent();
qDebug() << "Parent of m_timer2 is" << m_timer2->parent();
qDebug() << "Parent of m_timer3 is" << m_timer3->parent();@
Application output:
@Constructor object1, THREAD : 3055531792
Constructor object2, THREAD : 3055531792
Object2 process THREAD : 3019897712
Parent of m_timer is QObject(0x0)
Parent of m_timer2 is QObject(0x0)
Parent of m_timer3 is MyObject2(0x9563f20)
...@(Parent of m_timer and m_timer2 is QObject in my case)
BANG! I got it.
Thank you very much.Kay
-
I understand now that my m_timer object class member is not a child of my object.
But I still do not understand something.
I have done what Kay tried, so having three timers created in three different ways and qDebug the parent of those timers.You can see that m_timer2 has the same parent as m_timer but:
m_timer.start() is nok :
@QObject::startTimer: timers cannot be started from another thread@m_timer2->start() is ok:
signal/slot are working -
bq. Yes, m_timer and m_timer2 have the same parent, 0×0, which means that both have no parent.
Then why m_timer2 is able to be started from the thread and m_timer not?
I expect that m_timer2 is also not able to be started.
Is it because a new is done in the function process so in the thread, and then m_timer2 is really living in the thread since created in it? -
Because m_timer2 has been created after m_object2 has been moved to thread1, whereas m_timer is created before. The code in process() is executed in thread1, not the main thread.
An object always 'lives' in the thread it has been created (until moved to another thread of course).