common problem
Using the QPalette
setting QPushButton的背景
, it was found that it did not take effect.
Example
// 获取按钮的画刷
QPalette pal = ui->pushButton->palette();
// 使用颜色对话框选取颜色
QColor color = QColorDialog::getColor(color);
if (!color.isValid()) return;
// 设置画刷背景色,并将其应用到按钮上
pal.setBrush(QPalette::Background, color);
ui->pushButton->setPalette(pal);
这应该是新手最常见的错误用法
, But the result is not as expected.
Its running effect is shown in the figure:
problem analysis
- For QPushButton, you should not use
QPalette::Background
orQPalette::Window
to set the background color, but use itQPalette::Button
; - The attribute style of the button control is not set, including setting the background auto-fill, flat style, etc.
solution
Modify the code as follows:
// 设置按钮的属性
ui->pushButton->setAutoFillBackground(true); // 背景色自动填充
ui->pushButton->setFlat(true); // 样式扁平
// 获取按钮的画刷
QPalette pal = ui->pushButton->palette();
// 使用颜色对话框选取颜色
QColor color = QColorDialog::getColor(color);
if (!color.isValid()) return;
// 设置画刷背景色,并将其应用到按钮上
pal.setBrush(QPalette::Window, color);
ui->pushButton->setPalette(pal);
Run the program, the effect is as follows:
- setAutoFillBackground(true)
This code is to prevent the background color of the parent control from overwriting it QPushButton
, 背景色
which may be surprising, but this is the actual situation. Generally, you need to add this sentence when using QPalette to set the color.
- setFlat(true)
This sentence is QPushButton
specifically written for, and is explained in the Qt help document:
If 去掉
that line of code, then only 按钮边框会带有颜色,内部背景色不会生效
. The effect is shown in the figure:
- QPalette::Button
This code is for the QPushButton设置背景色
brush type used, 用其他类型会导致背景色不生效
.
If you think this article is helpful to you, you can like or follow it!
Those who have comments are welcome to leave a message at the bottom of the article~
Everything is possible, and I hope the world is better!