Background Worker in Qt

Coming from C#, Qt and its C++ base might not look the friendliest. One example is ease of BackgroundWorker and GUI updates. "Proper" way of creating threads in Qt is simply a bit more involved.

However, with some lambda help, one might come upon solution that's not all that different.

#include <QFutureWatcher>
#include <QtConcurrent/QtConcurrent>

QFutureWatcher watcher = new QFutureWatcher<bool>();
connect(watcher, &QFutureWatcher<bool>::finished, [&]() {
//do something once done
bool result = watcher->future().result();
QFuture<bool> future = QtConcurrent::run([]() {
//do something in background

QFuture is doing the heavy lifting but you cannot update UI from its thread. For that we need a QFutureWatcher that'll notify you within the main thread that processing is done and you get to check for result and do updating then.

Not as elegant as BackgroundWorker but not too annoying either.

Leave a Reply

Your email address will not be published. Required fields are marked *