Home > OS >  How to update value in progressBar in another thread in QT c
How to update value in progressBar in another thread in QT c

Time:04-18

I develop a qt program with an interface. I also have a complex calculation that is done on a separate thread from the ui thread. I want to update the progressBar from the thread in which the calculations are done. But I get an error that I cannot change an object that belongs to another thread.

Here is my code:

void Somefunc()
{
   ui->progressBar->setValue(progress);
}

void MainWindow::on_pushButton_3_clicked()
{
    auto futureWatcher = new QFutureWatcher<void>(this);
    QObject::connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater);
    auto future = QtConcurrent::run( [=]{ SomeFunc(); });

    futureWatcher->setFuture(future);
}

How correctly update the progress bar?

CodePudding user response:

Use a signal/slot combination, specifically the queued connection type (Qt::ConnectionType). So, along those lines:

void MainWindow::Somefunc()
{
   emit computationProgress(progress);
}

void MainWindow::setProgress(int progress)
{
   ui->progressBar->setValue(progress);
}

void MainWindow::on_pushButton_3_clicked()
{
    auto futureWatcher = new QFutureWatcher<void>(this);
    connect(futureWatcher, &QFutureWatcher<void>::finished, futureWatcher, &QFutureWatcher<void>::deleteLater);
    auto future = QtConcurrent::run( [=]{ SomeFunc(); });

    futureWatcher->setFuture(future);
    connect(this, &MainWindow::computationProgress, this, &MainWindow::setProgress, Qt::QueuedConnection);
}
  • Related