2016-09-05 53 views
1
void MainWindow::on_pushButton_clicked() 
{ 
    QFuture<int> future = QtConcurrent::run(identify); //Thread1 
    if (future.isFinished()) 
    { 
     //DoSomething();  
    } 
} 

我有這段代碼。識別功能完成運行後,我想運行DoSomething()功能。可能嗎?線程完成後,如何運行我的Qt函數?

+0

我已經試過了,問題是直到線程完成後,GUI仍然沒有響應。 –

回答

6

您可以將QFuture對象傳遞給QFutureWatcher,並將其finished()信號連接到函數或插槽DoSomething()

例如:

void MainWindow::on_pushButton_clicked() 
{ 
    QFuture<int> future = QtConcurrent::run(identify); //Thread1 
    QFutureWatcher<int> *watcher = new QFutureWatcher<int>(this); 
      connect(watcher, SIGNAL(finished()), this, SLOT(doSomething())); 
    // delete the watcher when finished too 
    connect(watcher, SIGNAL(finished()), watcher, SLOT(deleteLater())); 
    watcher->setFuture(future); 
} 

void MainWindow::DoSomething() // slot or ordinary function 
{ 
    // ... 
} 

或者你可以使用一個嵌套的事件循環,以保持GUI響應,並具有相同的功能,裏面的一切:

void MainWindow::on_pushButton_clicked() 
{ 
    QFuture<int> future = QtConcurrent::run(identify); //Thread1 
    QFutureWatcher<int> watcher; 
    QEventLoop loop; 
    // QueuedConnection is necessary in case the signal finished is emitted before the loop starts (if the task is already finished when setFuture is called) 
    connect(&watcher, SIGNAL(finished()), &loop, SLOT(quit()), Qt::QueuedConnection); 
    watcher.setFuture(future); 
    loop.exec(); 

    DoSomething(); 
} 
+0

connect(&watcher,SIGNAL(finished()),&myObject,SLOT(handleFinished())); 我有一個問題,我寫什麼,而不是&myObject和handleFinished? –

+0

@NemethAttila我加了2個例子。 – alexisdm

+0

謝謝,第二個例子正是我想要的。 –

相關問題