Solved 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) { ui->setupUi(this); connect(this, SIGNAL(updatePB()), this, SLOT(changeProgressBarValue())); ui->progressBar->setValue(0); } MainWindow::~MainWindow() { delete ui; } void MainWindow::changeProgressBarValue() { test=test + 3; int b = (test / 60) * 100; ui->progressBar->setValue(b); // ui->horizontalSlider->setValue(b); //QCoreApplication::processEvents(); //qApp->processEvents(); } void MainWindow::on_pushButton_clicked() { emit updatePB(); }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); int test=0; signals: void updatePB(); private slots: void on_pushButton_clicked(); void changeProgressBarValue(); private: 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 ?
thanks -
@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;
-