简体   繁体   中英

How can I run my Qt function after a thread has finished?

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

I have this code. I want to run the DoSomething() function after the identify function finished running. Is it possible?

You can pass the QFuture object to a QFutureWatcher and connect its finished() signal to the function or slot DoSomething() .

For example:

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
{
    // ...
}   

Or you could use a nested event loop to keep the GUI responsive and have everything inside the same function:

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();
}

I like this call layout.

auto watcher = new QFutureWatcher<int>(this);
connect(watcher, &QFutureWatcher<int>::finished,
    [watcher, this] ()
{
    watcher->deleteLater();
    auto res = watcher->result();
    // ...
});

watcher->setFuture(QtConcurrent::run(identify, param1, param2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM