C++ – How to use a QProgressBar

cprogress-barqt

I am trying to use a progress bar qt creator as a battery image, so I need to be able to control the progress bar(with a variable called my_value that I will change afterward).
To be more precise,I would like to be able to set from the program the value of the progress bar and have it actually changed and appear on the screen.
So far, I am rather lost :
-I created a progress bar named battery in the .ui file.
– I have not changed anything from the header file(that is automatically generated), but it this code :

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

-Here is my main.cpp file :

include "mainwindow.h"
#include <QApplication>
#include <QProgressBar>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QProgressBar battery;
    int my_value=10;
    battery.setValue(my_value);
    battery.valueChanged(my_value);
    MainWindow w;
    w.show();
    return a.exec();
}

I tried setValue() and valueChanged(), but neither of them work
So I tried with the mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProgressBar>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->battery->setValue(10);
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

but it still does not work.
Can someone help me ?

Thank you very much.

Best Answer

You don't need to create a QProgressBar in your main, it will automatically be created when you call new Ui::MainWindow().

void valueChanged() is a signal so you are not supposed to call it, but connect slots to it. I suggest you read this page if you are not familiar with Qt's signal/slots system: http://doc.qt.io/qt-5/signalsandslots.html

You should start by setting up the progress bar correctly in your MainWindow constructor:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{        
    ui->battery->setOrientation(Qt::Horizontal);
    ui->battery->setRange(0, 100); // Let's say it goes from 0 to 100
    ui->battery->setValue(10); // With a current value of 10

    ui->setupUi(this);
}

Then you should be able to create your own signals and connect them to void QProgressBar::setValue(int) to change the progress bar value. You can also call setValue() directly from where you are doing you are doing your processing if it is in scope.

Hope it helps!