QProgressBar blocked by main Thread?

800 views Asked by At

=======================================================

QProgressBar* pbar = new QProgressBar(this);
pbar->setMinimum(0);
pbar->setMaximum(0);
pbar->show();
for (int i = 0; i < 10000; i++) {
    qDebug() << "=====flag1======";
}
pbar->close();

===========================================================

I want the ProgressBar show busy when qDebug() message, but there is no effect, the QProgressBar was blocked and close when the loop finished.

Does anyone know how to solve this problem? thank you!

3

There are 3 answers

0
Tazo leladze On

Yes GUI Is Blocked, becose 10 000 it's a lot of time. Use QThread http://doc.qt.io/qt-4.8/qthread.html .

void My_Thread::run() {
    for (int i = 0; i < 1e4; i++) {
        if (i % 100 == 0) {
            emit UpdateProgressBar(i);
        }
    }
}



//In Your SLOT
void MainWindow::UpdateProgressbar(int value) {
    ui->progressbar->setValue(value);
} 
0
Vova Shevchyk On

Main threads is locked by loop before UI appears and UI is updated right after loop ends. If you want to see progress bar you can add QApplication::processEvents(); inside the loop. It's not the best solution but it will work.

0
Marek R On

To alow any widget to appear event loop has to be processed. Since you have full control over main thread its event loop is not able to process events which will show and update QProgressBar.

One way to fix if, which is quick but crapy is add to your loop QApplication::processEvents(); which process evens of event loop. Ofcaource you should also call bar->setValue(i);.

Proper way to do it is asynchronous programing which is using signals and slots. You didn't provide any details about your actual problem so can't provide good solution.