PDA

View Full Version : QProgressBar with % in decimal



buster
30th March 2020, 00:34
What is the best/easiest way to modify QProgressBar to show the %-value as a decimal value? I presume somebody will have done this before, but I have not been able to find it.

ChristianEhrlicher
30th March 2020, 05:34
See QProgressBar::format() (https://doc.qt.io/qt-5/qprogressbar.html#format-prop)

ChrisW67
30th March 2020, 08:21
Not sure I see how setFormat() can be used to get a percentage value that is not integer. The placeholder "%p" gets an integer as a string. You could get a string like "9 of 37" from "%v of %m" but you cannot compute with these placeholders.

You could subclass QProgressBar and override QProgressBar::text():


#ifndef FRACTIONALPROGRESSBAR_H
#define FRACTIONALPROGRESSBAR_H

#include <QProgressBar>

class FractionalProgressBar : public QProgressBar
{
public:
FractionalProgressBar(QWidget *p = nullptr);

// QProgressBar interface
public:
virtual QString text() const Q_DECL_OVERRIDE;
};

#endif // FRACTIONALPROGRESSBAR_H


#include "fractionalprogressbar.h"

FractionalProgressBar::FractionalProgressBar(QWidg et *p):
QProgressBar(p)
{
}


QString FractionalProgressBar::text() const
{
if ( minimum() == maximum() ) // divide by zero guard
return QString();

double percent = 100.0 * (value() - minimum()) / (maximum() - minimum());
return QString("%1%").arg(percent, 0, 'f', 1);
}

buster
30th March 2020, 15:39
But the setValue() method converts the input argument to int, so the fractional part of the value is lost.

d_stranz
30th March 2020, 18:51
But the setValue() method converts the input argument to int, so the fractional part of the value is lost.

Change the scale of the progress bar range. If you now have it set to range from 0 - 100, and you want one decimal place, change it to a range of 0 - 1000. Use ChrisW67's method to format the text by converting the value to a float, dividing by 10, and use the result to set a float formatted string.

You will also have to change the code that sets the value to multiply the number passed to setValue() by 10.

buster
31st March 2020, 06:22
Works perfectly! Thanks. I tried to find a good excuse for not thinking of this myself, but couldn't find one ...