Qt5 - setting background color to QPushButton and QCheckBox

Betty Crokker picture Betty Crokker · Feb 10, 2014 · Viewed 73.7k times · Source

I'm trying to change the background color of a QAbstractButton (either a QPushButton or QCheckBox) in Qt5 and having zero luck.

This does nothing:

pButton->setAutoFillBackground(true);
QPalette palette = pButton->palette();
palette.setColor(QPalette::Window, QColor(Qt::blue));
pButton->setPalette(palette);
pButton->show();

and if I try changing the style sheet:

pButton->setStyleSheet("background-color: rgb(255,255,0);");

then Qt throws up its hands and draws an afwul-looking blocky button.

There is a page titled "How to change the background color of QWidget" but it just talks about those two methods.

There is also a page "Qt Style Sheets Examples" that implies that if you want to change the background color, you have to take over all aspects of drawing the button, which just seems like overkill.

I need this to run on Mac, Windows, and Ubuntu Linux, and it's really not a happy thing if I have to manually draw everything about the button 3 times (once for each platform).

Am I missing something obvious?

p.s. By "background color" I mean the area surrounding the button, not the color under the text on the face of the button.

Answer

Alchete picture Alchete · Apr 29, 2014

I had the same issue, but finally got this to work. I'm using Qt 5 with the Fusion color theme:

QPalette pal = button->palette();
pal.setColor(QPalette::Button, QColor(Qt::blue));
button->setAutoFillBackground(true);
button->setPalette(pal);
button->update();

Try these commands in the exact order as above, and if that still doesn't work, set your theme to Fusion and try again.

Good luck!