做项目的时候,自定义了一个继承自QWidgetde的组件,设置样式表无效,然后用QPalette设置背景颜色还是无效,但是设置autoFillBackground为true后发现调色板属性可以生效,查阅Qt文档
autoFillBackground : bool
This property holds whether the widget background is filled automatically.
If enabled, this property will cause Qt to fill the background of the widget before invoking the paint event. The color used is defined by the QPalette::Window color role from the widget's palette.
In addition, Windows are always filled with QPalette::Window, unless the WA_OpaquePaintEvent or WA_NoSystemBackground attributes are set.
This property cannot be turned off (i.e., set to false) if a widget's parent has a static gradient for its background.
Warning: Use this property with caution in conjunction with Qt Style Sheets. When a widget has a style sheet with a valid background or a border-image, this property is automatically disabled.
By default, this property is false.
可以得到以下信息:
- 如果此属性可用,那么在调用重绘事件前会用窗口的画板属性自动填充窗口,
- 窗口总是用QPalette::Window的颜色来填充
- 如果父亲的窗口有渐变色填充那么该属性一定是可用的
- 如果和样式表混合使用,那么样式表中的背景颜色和图片属性会使该属性失效
继承自qwidget的组件没有重写绘图事件的话,预览(alt+shift+R)可以显示画板设置的属性,样式表在预览和运行后都会失效,如果该属性为false运行后窗口没有背景颜色,为true的话则显示画板属性的颜色,而样式表是绘图事件通过paint来显示出来的。
解决方法:
重写绘图事件
#include <qpaint.h>
void paintEvent(QPaintEvent*)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
网友评论