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.

[type title=“Code”] #include #include ``…`` QFutureWatcher watcher = new QFutureWatcher(); connect(watcher, &QFutureWatcher::finished, [&]() { //do something once done bool result = watcher->future().result(); }); QFuture future = QtConcurrent::run([]() { //do something in background }); watcher->setFuture(future); [/type]

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.