首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在QT c++中的另一个线程中更新progressBar中的值

如何在QT c++中的另一个线程中更新progressBar中的值
EN

Stack Overflow用户
提问于 2022-04-14 17:50:10
回答 1查看 215关注 0票数 -2

我开发了一个带有接口的qt程序。我还有一个复杂的计算,它是在独立于ui线程的线程上完成的。我想从执行计算的线程中更新progressBar。但我得到一个错误,无法更改属于另一个线程的对象。

这是我的代码:

代码语言:javascript
复制
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);
}

如何正确地更新进度条?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-14 18:04:06

使用信号/时隙组合,特别是排队连接类型(Qt::ConnectionType)。因此,按照这样的思路:

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71875808

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档