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

私はこのコードを持っています。私はDoSomething()関数を実行したいと思います。出来ますか?スレッドが終了した後でQt関数を実行するにはどうすればよいですか?

+0

私はそれを試したし、問題がありますスレッドが終了するまで、GUIは応答しなくなります。 –

答えて

6

QFutureWatcherQFutureオブジェクトを渡し、その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

ありがとうございました.2番目の例は、まさに私が望んでいたものです。 –

関連する問題