QObject :: moveToThread and the execution of a member function inside this thread

If an object of type QObject moved to a thread using QObject::moveToThread , all signals that the object receives are processed inside this thread. However, if the slot is called directly ( object->theSlot() ), the call will still be blocked. What would be the usual way to make this call inside the thread and immediately return control to the calling thread? Hacks with QTimer not taken into account. Setting up a single-purpose connection and deleting it again can be considered a solution if all else fails.

+4
source share
2 answers

You can use QMetaObject::invokeMethod with Qt :: ConnectionType set to Qt :: QueuedConnection

+5
source

You can use QFuture<T> QtConcurrent::run ( Function function, ... ) to run some execution inside a separate thread, and then use QFutureWatcher to get the result. You will not need to call movetoThread .

Basically something like:

 QFutureWatcher<T>* watch = new QFuture(0); connect(watch, SIGNAL(finished()), this, SLOT(handleResult())); QFuture<T> future = QtConcurrent::run( myObj, &QMyObject::theSlot(), args...); watch.setFuture(future); .... //slot private void handleResult(){ if(future->isCancelled()) return; T mydata = watch->future()->result(); // use your data as you want } 

QtConcurrent::run will schedule the launch of this object in some thread. It does not block. On the other hand, QFuture::result() blocks until a result is obtained if the calculation is still ongoing. To do this, you need another object to be notified when the calculation is completed using finished() . I cannot come up with a better design for your problem in Qt.

0
source

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


All Articles