简体   繁体   English

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

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

This is what I have: 这就是我所拥有的:

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

It works, the job in the thread gets done, and the progress bar goes all the way up to 100%. 它可以正常工作,线程中的工作已完成,进度条一直上升到100%。

But the UI is completely frozen/laggy. 但是 ,UI完全冻结/缓慢。 Dragging a window with the progress bar results in a 5 second delay. 拖动带有进度栏的窗口会导致5秒钟的延迟。 I tried using lower thread priorities - no result. 我尝试使用较低的线程优先级-没有结果。

Maybe I need a mutex here? 也许我这里需要互斥锁?

Do not emit too many progressChanged signals. 不要发出太多的progressChanged信号。 Signals are fast, but if you are setting progress bar value hundreds or thousands times per second, the UI will freeze. 信号速度很快,但是如果您每秒设置数百或数千次进度条值,则UI会冻结。 Keep the progress bar changes to minimum, 5-10 changes per second is more than enough. 保持进度栏更改为最小,每秒5-10次更改已足够。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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