setStyleSheet不生效原因總結
1、繼承自QWidget但未重寫paintevent
解決方案:
參考官方文檔subclass from QWidget
If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below:
void CustomWidget::paintEvent(QPaintEvent *)
{
QStyleOption opt;
opt.init(this);
QPainter p(this);
style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
The above code is a no-operation if there is no stylesheet set.
2、父組件中對子組件setStyleSheet(或在父組件中對子組件styleSheet做更改),導致子組件中setStyleSheet內容被覆蓋掉
對於一個子組件,其styleSheet可以在以下幾個地方設置:
子組件ui中設置
、子組件源碼中設置
、父組件ui中設置
、父組件源碼中設置
這幾個地方setStyleSheet,執行時的順序是怎樣的?
在xxx.cpp和ui_xxx.cpp文件中找到對應的setStyleSheet下斷點可知執行順序為:
子組件ui中設置
->子組件源碼中設置
->父組件ui中設置
->父組件源碼中設置
解決方案:
盡量規范約定好setStyleSheet位置,如自定義子組件僅在子組件中setStyleSheet,父組件不重復設置,防止setStyleSheet覆蓋
3、stylesheet中使用了屬性作為選擇器,但屬性切換時沒有polish()
解決方案:
例如以下的styleSheet:
QPushButton[stateColor='red']
{
background-color: rgb(170, 0, 0);
}
QPushButton[stateColor='green']
{
background-color: rgb(0, 170, 0);
}
使用時,想要切成綠色,
ui->pushButton->setProperty("stateColor","green");
ui->pushButton->style()->unpolish(ui->pushButton);
ui->pushButton->style()->polish(ui->pushButton);