简体   繁体   中英

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%.

But the UI is completely frozen/laggy. Dragging a window with the progress bar results in a 5 second delay. I tried using lower thread priorities - no result.

Maybe I need a mutex here?

Do not emit too many progressChanged signals. Signals are fast, but if you are setting progress bar value hundreds or thousands times per second, the UI will freeze. Keep the progress bar changes to minimum, 5-10 changes per second is more than enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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