How to effectively set the background of QPushButton

common problem

Using the QPalettesetting 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:

Background color is not effective

problem analysis

  • For QPushButton, you should not use QPalette::Backgroundor QPalette::Windowto set the background color, but use it QPalette::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:

Effective button background color

  • 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 QPushButtonspecifically written for, and is explained in the Qt help document:

The official document about flat

If 去掉that line of code, then only 按钮边框会带有颜色,内部背景色不会生效. The effect is shown in the figure:

Button border background color

  • 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!


Guess you like

Origin blog.csdn.net/gkzscs/article/details/102458849