Reputation: 3124
I have an App that consumes lots of time running an algorithm. When the filter is running, the GUI obviously blocks until the algorithm is finished.
For that reason I want to show a modal dialog while the algorithm runs, displaying a "Busy" message. This way, the GUI would still be responsive. I tried doing it as follows:
dialog->setModal(true);
dialog->show();
// Run the code that takes up a lot of time
....
dialog->close();
However, this way the dialog shows up but it's all black (it's not drawn), Hoe can I solve this?
Upvotes: 1
Views: 639
Reputation: 1223
If GUI has to be responsive, heavy algorithm should run in non-main (non-GUI) thread. To be responsive, GUI has to have access to main thread to process events in event loop.
You can use QFuture
with QtConcurrent::run
to implement this.
Example of QFuture
usage:
TAlgoResult HeavyAlgorithm() {/* Here is algorithm routine */};
QFuture<TAlgoResult> RunHeavyAlgorithmAsync()
{
QtConcurrent::run([&](){return HeavyAlgorithm();});
}
// class which calls algo
class AlgoCaller
{
QFutureWatcher<TAlgoResult> m_future_watcher;
QDialog* mp_modal_dialog;
AlgoCaller()
{
QObject::connect(&m_future_watcher, &QFutureWatcher<void>::finished,
[&]()
{
mp_modal_dialog->close(); // close dialog when calculation finished
})
}
void CallAlgo() // to be called from main thread
{
mp_modal_dialog->show(); // show dialog before algo start
m_future_watcher.setFuture(RunHeavyAlgorithmAsync());
// start algo in background
// main thread is not blocked and events can be processed
}
};
Upvotes: 3