Qt繁忙处理对话框

问题描述:

我有一个应用程序需要耗费大量时间来运行算法。当过滤器运行时,GUI显然会阻塞,直到算法结束。Qt繁忙处理对话框

因此,我想在算法运行时显示模态对话框,显示“忙”消息。这样,GUI仍然可以响应。我试着做如下:

dialog->setModal(true); 
dialog->show(); 

// Run the code that takes up a lot of time 
.... 

dialog->close(); 

然而,这样的对话显示出来,但它是全黑的(它未画出),锄我能解决这个问题?

+3

你在注释代码阻塞事件循环处理的可能性最大。将其移动到另一个执行线程。 – StoryTeller

如果GUI必须响应,那么繁重的算法应该在非主(非GUI)线程中运行。 要做出反应,GUI必须能够访问主线程来处理事件循环中的事件。

您可以使用QFutureQtConcurrent::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 
    } 

}; 
+0

有没有可能提供一个例子? – manatttta

+0

@manatttta提供。请看看是否有帮助 –

+0

小心,'close'方法不是线程安全的,你不能从另一个线程调用它! –