pmr
pmr

Reputation: 59811

QObject::moveToThread and executing a member function inside that thread

If an object of type QObject is moved to a thread with QObject::moveToThread, all signals that the object receives are handled inside that thread. However, if a slot is called directly (object->theSlot()) that call will still block. What would be the normal way of executing that call inside the thread and returning control to the calling thread immediately? Hacks with QTimer don't count. Setting up a single purpose connection and deleting it again might count as a solution if all else fails.

Upvotes: 4

Views: 1539

Answers (2)

Kamil Klimek
Kamil Klimek

Reputation: 13130

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

Upvotes: 5

UmNyobe
UmNyobe

Reputation: 22890

You can use QFuture<T> QtConcurrent::run ( Function function, ... ) to launch 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 method of this object to be ran in some thread. It is non-blocking. On the other hand, QFuture::result() blocks until there is a result, if the computation is still ongoing. That's why you need the other object to notify when the computation is over using finished(). I cannot think of a better design for your problem in Qt.

Upvotes: 0

Related Questions