2017-07-17 88 views
1

我有一個應用程序需要耗費大量時間來運行算法。當過濾器運行時,GUI顯然會阻塞,直到算法結束。Qt繁忙處理對話框

因此,我想在算法運行時顯示模態對話框,顯示「忙」消息。這樣,GUI仍然可以響應。我試着做如下:

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

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

dialog->close(); 

然而,這樣的對話顯示出來,但它是全黑的(它未畫出),鋤我能解決這個問題?

+3

你在註釋代碼阻塞事件循環處理的可能性最大。將其移動到另一個執行線程。 – StoryTeller

回答

3

如果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'方法不是線程安全的,你不能從另一個線程調用它! –