做項目的時候拔恰,自定義了一個繼承自QWidgetde的組件屁置,設置樣式表無效,然后用QPalette設置背景顏色還是無效仁连,但是設置autoFillBackground為true后發(fā)現(xiàn)調色板屬性可以生效蓝角,查閱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);
}