I have a thread created by inheriting QThread
in which I called exec()
to initiate the event loop. And this class that inherits QThread
has a method in it.
How can I call that method from the main thread for it to execute in the child thread?
I assume that the execution of that method has to be queued in the child thread's event loop, so calling threadObject->childThreadMethod()
won't be a good idea.
Is there any solution to this?
You can not call every member functions of the thread, but only slots and Q_INVOKABLE methods.
Use QMetaObject::invokeMethod()
to call such a method, and make sure to set the connection type to Qt::QueuedConnection
.
That way, the method will be called in the second thread whenever the control returns to the event loop in the second thread. The caller, i.e. the main thread, will continue immediately, so you won't be able to get a return value from the called method.
Behind the scenes, QMetaObject::invokeMethod
adds a MetaCallEvent
to the second thread's event queue.
Alternatively, create a signal/slot connection, and then emit a signal whenever you want the slot to be called in the other thread.