Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt5 - setting background color to QPushButton and QCheckBox

Tags:

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.

like image 211
Betty Crokker Avatar asked Feb 10 '14 18:02

Betty Crokker


People also ask

How to set background Color for pushButton in Qt?

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


2 Answers

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!

like image 69
Alchete Avatar answered Sep 17 '22 12:09

Alchete


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.

like image 42
abaghiyan Avatar answered Sep 20 '22 12:09

abaghiyan