Amor_aeternus
Amor_aeternus

Reputation: 31

QProgressBar blocked by main Thread?

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

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!

Upvotes: 0

Views: 858

Answers (3)

Marek R
Marek R

Reputation: 37882

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.

Upvotes: 1

Vova Shevchyk
Vova Shevchyk

Reputation: 138

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.

Upvotes: 1

Tazo leladze
Tazo leladze

Reputation: 1489

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

Upvotes: 3

Related Questions