PDA

View Full Version : Setting Background Color



SixDegrees
15th February 2011, 23:11
I have several buttons on my application that have their background color set dynamically during runtime to reflect associated displayed data. This works fine - on some platforms. On others, the button background refuses to change. I'm not using stylesheets - I use the following construct:


QPalette p = visibleButton->palette();
p.setColor(QPalette::Button, newColor);
visibleButton->setPalette(p);

I've also tried placing a small, blank label next to the button and changing it's background color using the same approach. This also fails on some platforms but succeeds on others.

What is the recommended way of setting the background color of a button, or a widget in general, that will work everywhere?

high_flyer
16th February 2011, 10:21
What is the recommended way of setting the background color of a button, or a widget in general, that will work everywhere?
The approach you are taking is the correct one.
But it could be that there is issue with the roles.
Try to play with the color roles.
If what you want is background, try using QPalette::Window and not QPalette::Button for example.
It probably has to do with the following:

The general button background color. This background can be different from Window as some styles require a different background color for buttons.

SixDegrees
16th February 2011, 14:08
I tried various combinations of QPalette::Window and QPalette::Button; still no joy.

high_flyer
16th February 2011, 14:19
Hmm...
Which platforms work and which don't?

I would try stepping through the Qt code - and compare what is the difference between the working and the non working.
It might be even a Qt bug.

mattc
16th February 2011, 15:28
You might also try experimenting with QWidget::setAutoFillBackground(true/false)

SixDegrees
16th February 2011, 18:33
I fiddled some more, and never had any luck with the button backgrounds. I suspect it requires stylesheets to make it work, and that's just too much effort for something as conceptually simple as 'setBackground(myColor)'. So I went back to the color swatch approach and got that working after a fair amount of fiddling.

It was failing on Windows and on some Linux distros; other Linux distros worked just as I expected them to. So I don't think chasing platform-specific code variations is worthwhile, and it's something I just don't have time for anyway.