PDA

View Full Version : Changing colors of QProgressBar



mastupristi
17th January 2012, 10:18
Hi,

I need to change the color of a progress bar depending on its value.

I tried in some ways with poor results.



QPalette pal = ui->progressBar->palette();
pal.setColor(QPalette::Normal, QPalette::Base, QColor("red"));
//pal.setColor(QPalette::Highlight, Qt::red);
//pal.setColor(QPalette::Background, Qt::red);
ui->progressBar->setPalette(pal);


I also tried to change stylesheet from QT Creator, but nothing happens.

where am I wrong?

I'm using Qt 4.7, QT Creator 2.0.1, Ubuntu 10.10 64 bit.

thanks

Lykurg
17th January 2012, 11:59
You have to alter QPalette::Highlight, but it also depends on your used window style.

That works
#include <QtGui>

int main(int argC, char **argV)
{
QApplication::setStyle(new QWindowsStyle);
QApplication myApp(argC, argV);

QProgressBar bar;
bar.setRange(0,100);
bar.setValue(50);
QPalette p = bar.palette();
p.setColor(QPalette::Highlight, Qt::red);
bar.setPalette(p);
bar.show();

return myApp.exec();
}

MarekR22
17th January 2012, 12:20
First of all palette works as a difference property. If something is missing it is taken from parent if there is no parent it is taken from QApplication (which always has fully resolved palette), so you don't have to fetch anything (and you shouldn't set full palette).

My question is how you are do that? When this code is invoked?

I would do new QObject for that:

class MyPaletteChanger : public QObject {
Q_OBJECT

....

public slots:
void setColorProgress(int value) {
QColor color(someFunciton(value));
if (color != lastColor) {
lastColor = color;
QPalette palette;
palette.setBrush(QPalette::Highlight, QBrush(color));
emit newPallete(palette);
}
}

signals:
void newPallete(const QPalette &palette);
}
Then connect valueChange of progress bar with setColorProgress and newPallete with setPalette of progress bar.

Lykurg
17th January 2012, 12:42
First of all palette works as a difference property.
Nice, I wasn't aware of that. Thanks.