Search code examples
qtqprogressbar

How to make the value of QProgressBar start from 0?


In the function - loadData(), First, show the dialog with QProgressBar,and then, call setValue() for the progressbar base on the business. when the value of progressbar increase to 100%, hide the dialog and set the value to 0.

My question is: When I enter the loadData() function again, after exec the dlgo->show(), the value of progressbar isn't start from 0, but jump from 100 to 0, and then go on.

What can I do to make the value of progressbar start from 0 when I tried show the dialog again? Thank you!

void loadData() {
    mProcessBarDlg->show();

    {
      mProcessBarDlg->ui.progressBar->setValue(XX);
    }

    mProcessBarDlg->hide();
    mProcessBarDlg->ui.progressBar->setValue(0);
}

Solution

  • Set it to zero before you show it.

    EDIT: The following code, derived from the poster's question, works:

    #include <qapplication.h>
    #include <qdialog.h>
    #include <qprogressbar.h>
    
    QDialog *mProcessBarDlg;
    QProgressBar *progressBar;
    
    void loadData() {
        mProcessBarDlg->setValue(0);
        mProcessBarDlg->show();
    
        for (int i = 0; i < 100000000; ++i){
            if (i % 100 == 0){
                qApp->processEvents();
            }
        }
    
        {
          progressBar->setValue(50);
          for (int i = 0; i < 100000000; ++i){
            if (i % 100 == 0){
                qApp->processEvents();
            }
          }
        }
    
        mProcessBarDlg->hide();
    }
    
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        mProcessBarDlg = new QDialog;
        progressBar = new QProgressBar(mProcessBarDlg);
    
        loadData();
    
        for (int i = 0; i < 100000000; ++i){
            if (i % 100 == 0){
                a.processEvents();
            }
        }
    
        loadData();
    
        QMetaObject::invokeMethod(&a, "quit", Qt::QueuedConnection);
    
        return a.exec();
    }