Qt World Summit: Submit your Presentation

QProgressbar not updating

  • Hello

    i am trying to use a progress bar but it is not updating when i set new value to it.
    So far i read few thread and posts here and there, speaking about using threads etc. i tried bunch of things, nothing working except some examples showing a slider being connected to a progress bar, but it is not what i want.

    here is my test code:

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QObject>
    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    connect(this, SIGNAL(updatePB()), this, SLOT(changeProgressBarValue()));
        delete ui;
    void MainWindow::changeProgressBarValue()
        test=test + 3;
        int b = (test / 60) * 100;
       // ui->horizontalSlider->setValue(b);
    void MainWindow::on_pushButton_clicked()
        emit updatePB();
    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    #include <QMainWindow>
    namespace Ui { class MainWindow; }
    class MainWindow : public QMainWindow
        MainWindow(QWidget *parent = nullptr);
        int test=0;
        void updatePB();
    private slots:
        void on_pushButton_clicked();
        void changeProgressBarValue();
        Ui::MainWindow *ui;
    #endif // MAINWINDOW_H

    in this example the progress bar should change when i click a button, but it is not changing, it only changes when i click the button 20 times, because the value reaches 100%

    Also this example is based on some recommandations i read but in my case i want the progress bar to update immediatly when i change its value (i dont want to use a thread or a signal/slot), i have tried to call processEvents() but this did not work too...

    Any idea to get the progress bar works ?

  • @Xena_o looks like integer division is happening here

    int b = (test / 60) * 100;

    change it to 60.0 it will work
    int b = (test / 60.0) * 100;

  • @nagesh ugh! i wasted so much time because of a .0 !!!
    thank you !

  • Performing the multiplication first avoids the need to convert to floating point to reduce precision loss. It is also likely faster.

    int b = (test * 100) / 60;

  • @Xena_o
    I agree with @jeremy_k. No point doing floating point anything when integer division will do! I would suggest a slight amendment:

    int b = (test * 100 + 30) / 60;

    rounds to nearest instead of flooring :)

Log in to reply