我有一个应用程序,它运行一个算法需要花费大量时间。当过滤器运行时,GUI 显然会阻塞,直到算法完成。
出于这个原因,我想在算法运行时显示一个模态对话框,显示一条“忙碌”消息。这样,GUI 仍然可以响应。我尝试按如下方式进行:
dialog->setModal(true);
dialog->show();
// Run the code that takes up a lot of time
....
dialog->close();
但是,这样显示出来的dialog却是全黑的(没有画出来),哎,请问这个问题能解决吗?
最佳答案
如果 GUI 必须响应,重型算法应该在非主(非 GUI)线程中运行。 为了响应,GUI 必须能够访问主线程以在事件循环中处理事件。
您可以使用 QFuture
和 QtConcurrent::run
来实现它。
QFuture
用法示例:
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
}
};
关于c++ - Qt 忙处理对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45141545/