繼承自QWidget的組件樣式表無用的解決方法

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

可以得到以下信息:

  1. 如果此屬性可用,那么在調(diào)用重繪事件前會用窗口的畫板屬性自動填充窗口,
  2. 窗口總是用QPalette::Window的顏色來填充
  3. 如果父親的窗口有漸變色填充那么該屬性一定是可用的
  4. 如果和樣式表混合使用,那么樣式表中的背景顏色和圖片屬性會使該屬性失效

繼承自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);
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,618評論 19 139
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa閱讀 9,066評論 0 6
  • ¥開啟¥ 【iAPP實現(xiàn)進入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 7,357評論 0 17
  • 文/吃飽了睡 -1- 許多年后,我再回首大學時光。 我的腦海中,有特別深刻的一個片段,是曾經(jīng)一段極其墮落的過往。 ...
    吃飽了睡閱讀 1,431評論 12 47
  • 無論是古人感慨云:“讀萬卷書,行萬里路”,還是今人高歌:“生活不只眼前的茍且,還有詩和遠方的田野”,都一再提醒...
    小石榴姐姐閱讀 587評論 0 2

友情鏈接更多精彩內(nèi)容