'How to update value in progressBar in another thread in QT c++

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1