8

I am trying to make a simple example with QProgressDialog. So I have one QPushButton in a widget and when I press it, a QProgressDialog appears, progresses until 100 and then hides.

My problem is that if I click the save button for the second time, the QProgressDialog just appears and disappears.

The code of my slot that is called when the user presses the button:

progressDialog->show();
progressDialog->setWindowModality(Qt::WindowModal);
for(int i = 0; i <= 100; ++i)
{
    progressDialog->setValue(i);

    if(progressDialog->wasCanceled())
        break;
}

1 Answer 1

15

You need to allow the GUI to update/redraw itself. It doesn't do that on every setXXX call as it is too expensive and unnecessary. However, a redraw() event is queued so if you allow Qt to process events, the dialog will update.

Simply add the following inside your for loop, and read it's documentation for further usage scenarios:

 QApplication::processEvents();

Also, the loop you have runs far too fast for anything to be shown. Add a sleep call or do some useful work in order to see anything.

Update (thx Tim)

You might want to use QApplication::processEvents( QEventLoop::ExcludeUserInputEvents) to disallow user events (there's also an option for network events). They may trigger other parts in your application and cause re-entrancy and other unwanted control-flow.

But in your case, you probably want to include user events to get the cancel button.

1
  • 3
    As an addition, sometimes you want to supply an argument: QApplication::processEvents( QEventLoop::ExcludeUserInputEvents ) in order to allow only internal events like repaint etc. Events like mouse button presses and key presses are delayed until execution returns to the event loop. This may be vital if you don't want to allow user input to interrupt your operation. Just keep in mind the user can't press any button (e.g. Cancel button) in that case.
    – Tim Meyer
    Commented Dec 6, 2011 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.