在 QThread 中运行长时间操作并将信号发送到主线程仍会冻结 UI

Running a long operation in QThread and sending signals to the main thread still freezes the UI

本文关键字:线程 UI 冻结 信号 运行 QThread 长时间 操作      更新时间:2023-10-16

这是我所拥有的:

void MyThread::run() {
  int progress = 0;
  while (1) {
    // do something
    progres++;
    emit(progressChanged(progress));
  }
}
// mainwindow
auto t = new MyTread();
connect(t, SIGNAL(progressChanged(int)), this, SLOT(onProgressChanged(int)));
t->start();
void MaiWindow::onProgressChanged(int) {
  this->progressBar->setValue(progressBar->value() + 1);
}

它有效,线程中的工作完成,进度条一直上升到 100%。

但是 UI 完全冻结/滞后。拖动带有进度条的窗口会导致 5 秒的延迟。我尝试使用较低的线程优先级 - 没有结果。

也许我在这里需要一个互斥锁?

不要发出太多进度更改的信号。信号很快,但如果您每秒设置进度条值数百或数千次,UI 将冻结。将进度条更改保持在最低限度,每秒 5-10 次更改绰绰有余。