Search code examples
qtqtwidgets

Showing progress window while creating other window/widgets


I have a function that looks like the following

void MainWindow::CreateEnvironment()
{
    MdiWindow* sub = createSubWindow();
    MyQTWidget* widget = CreateWidget();
    ..
    ..
}

I want that during this function a progress bar will be shown at the beggining and will close at the end of this function. However adding

void MainWindow::CreateEnvironment()
{
    **progressBarDialog->show();**
    
    MdiWindow* sub = createSubWindow();
    MyQTWidget* widget = CreateWidget();
    ..
    ..
    **progressBarDialog->hide();**

}

Does not work, maybe because the function needs to exit first or something. What is the best way to do this?


Solution

  • I assume that you use QProgressDialog?

    You need to first setup the dialog with the correct number of steps you expect, how long you want to wait before it actually shows and more importantly: you need to call setValue() to update the progress bar.

    Here is an example of how I would solve that (as far as I understand it)

    void MainWindow::CreateEnvironment()
    {
        auto bar = new QProgressBarDialog(this);
        bar->setLabelText(tr("Creating Environment..."));
        bar->setCancelButton(nullptr); // No cancel button
        bar->setRange(0, 10);          // Let's say you have 10 steps
        bar->setMinimumDuration(100);  // If it takes more than 0.1 sec -> show the dialog
        
        bar->setValue(0);
        MdiWindow* sub = createSubWindow();
    
        bar->setValue(1);
        MyQTWidget* widget = CreateWidget();
        ..
        ..
        bar->setValue(10);
        MyLastWidget* last = CreateLastWidget();
    
        bar->deleteLater(); // Not needed anymore, let's get rid of it
    }
    

    And don't worry too much if the dialog never shows. Unless you're doing really heavy computation (such as allocating / initialising huge portion of memory), creating widgets is very fast and would finish before the 100ms times out.

    EDIT: Another thing to be aware of: QProgressDialog is meant to work after the main event loop started. (That is after the call to app.exec() in your main())

    If you plan to show call this function in the constructor of your MainWindow, the dialog might even never show up because the window itself is not fully created and operational.

    If you intended to call this function later, when the main window is already displayed on screen and the user hit a New Document button of some sort: you can ignore this part of the answer.