New blog location
New blog location
QFutureWatcher
QFutureWatcher
is useful in keeping track of when an asynchronous task complete. Consider a scenario where a dialog pops up while some operation runs in the background. The first step is to show the dialog:
msgDialog = new MessageDialog(); msgDialog->show(); QApplication::processEvents(); //needed to properly show the dialog
Having a QFuture m_OperationFuture
as a field, a naive approach to keeping the GUI responsive while the background operation takes place is to keep calling QApplication::processEvents()
while the operation is still executing:
m_OperationFuture = QtConcurrent::run(runBackgroundOperation); while(m_OperationFuture.isRunning()) { QApplication::processEvents(); } performNextOperation();
However, QFutureWatcher
provides a better alternative:
QFutureWatcher<QString> *watcher = new QFutureWatcher<QString>(this); QObject::connect(watcher,SIGNAL(finished()),this,SLOT(operationFinished())); m_OperationFuture = QtConcurrent::run(runBackgroundOperation); watcher->setFuture(m_OperationFuture);
In the operationFinished()
function, the result can be retrieved and the dialog can be closed:
QString err = m_OperationFuture.result(); closeDialog();
Comments
Post a Comment