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.
pButton->setAutoFillBackground(true); QPalette palette = pButton->palette(); palette. setColor(QPalette::Window, QColor(Qt::blue)); pButton->setPalette(palette); pButton->show();
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!
Try this:
QColor col = QColor(Qt::blue); if(col.isValid()) { QString qss = QString("background-color: %1").arg(col.name()); button->setStyleSheet(qss); }
as mentioned at the QT Forum by @goetz.
I used some different definition of Qcolor col
as QColor col = QColor::fromRgb(144,238,144);
and this works for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With