Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

qt - Qt5 - setting background color to QPushButton and QCheckBox

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...