如何在线程完成后运行我的Qt函数?

Nem*_*ila 2 c++ qt multithreading qtconcurrent

void MainWindow::on_pushButton_clicked()
{
    QFuture<int> future = QtConcurrent::run(identify);  //Thread1
    if (future.isFinished())
    {
       //DoSomething();    
    }
}
Run Code Online (Sandbox Code Playgroud)

我有这个代码.我想DoSomething()在识别功能运行完毕后运行该功能.可能吗?

ale*_*sdm 7

您可以将QFuture对象传递给a 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
{
    // ...
}   
Run Code Online (Sandbox Code Playgroud)

或者您可以使用嵌套的事件循环来保持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();
}
Run Code Online (Sandbox Code Playgroud)

  • @NemethAttila注意本地事件循环。最好是尽可能避免它们。 (2认同)
  • @NemethAttila因为在处理事件时可能发生很多事情。例如,您的`this`对象可能被删除。 (2认同)