因需要,需要重繪窗口的標題欄。
標題欄通過QWidget實現,可是當使用QPalette設置窗口的背景色后沒有效果。
代碼如下:
//QWidget類構造函數內 QPalette p; p.setBrush(this->backgroundRole(),QBrush(QColor(51,51,51))); this->setPalette(p);
如果這個QWidget直接show,是有背景色的,但是如果把它放到一個父Widget中時,它就沒有了效果。
后來通過網上搜索,發現添加如下代碼后就可以了:
//QWidget類構造函數內 this->setAutoFillBackground(true);
於是翻看幫助文檔的autoFillBackground屬性,我翻譯如下:
QWidget的autoFillBackground屬性 bool類型 這個屬性決定widget的背景色是否自動填充。 如果bool為真,這個屬性會在widget觸發PaintEvent之前引起Qt填充QWidget的背景色。 填充的顏色是由widget的QPalette::window顏色角色所決定的。 如果該widget沒有設置WA_OpaquePaintEvent屬性或者WA_NoSystemBackground屬性,windows總是會使用QPalette::window顏色角色。 注意:如果widget的父窗口有漸變的背景色填充,那么這個屬性是不能被關閉的(也就是不能設置為false)。 警告:混合使用此屬性和Qt style sheet的時候需要注意,當一個widget擁有一個style sheet設置的背景色或者border-image,那么autoFillBackground屬性自動關閉。 該屬性默認是關閉狀態。
查看QPalette::window,它為一個窗口的標准的背景色。
然后查看QPalette的說明,發現有下面一句說明:
When you assign a new palette to a widget, the color roles from this palette are combined with the widget's default palette to form the
widget's final palette. The palette entry for the widget's background role is used to fill the widget's
background (see QWidget::autoFillBackground), and the foreground role initializes QPainter's pen.
我的翻譯就是:
When you assign a new palette to a widget, the color roles from this palette are combined with the widget's default palette to
form the widget's final palette. The palette entry for the widget's background role is used to fill the widget's
background (see QWidget::autoFillBackground), and the foreground role initializes QPainter's pen. 當為widget設置一個新的palette的時候,那么設置的palette和widget的默認palette組合成最終的palette。這個palette調色板的背景角色用於填充widget 的背景色(autoFillBackground),同樣,前景角色用來初始化筆的顏色,也就是前景色。
既然setPalette是能夠設置窗口的背景色,而且當widget沒有父窗口是能夠成功設置背景色的。
於是我感覺問題可能是出在這句話:
如果該widget沒有設置WA_OpaquePaintEvent屬性或者WA_NoSystemBackground屬性,windows總是會使用QPalette::window顏色角色。
於是在構造函數和paintEvent中都qDebug輸出this->Palette().background();
發現結果是一樣的,這就證明問題不是出在這個位置。
仔細觀看setPalette的說明發現:
QWidget propagates explicit palette roles from parent to child. If you assign a brush or color to a specific role on a palette and assign that palette to a widget, that role will propagate to all the widget's children, overriding any system defaults for that role. 也就是說widget會清晰的傳遞自己的palette到孩子類。
於是我把父窗口的背景色設置為紅色,發現widget的背景色也是紅色了(通過qDebug輸出widget的background根本不是紅色)。
這也就是說明,如果沒有設置autoFillBackground,那么子窗口的setPalette是不生效的。也就是會是使用從父類傳遞來的"默認"背景色。
我說大牛門把setAutoFillBackground函數的釋義為不從父窗口繼承背景色,當初我還有點懷疑,現在算是理解了,雖然不知道對不對。 新手,學習ing...