Qt setStyleSheet不生效解决办法总结

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);
原文地址:https://www.cnblogs.com/SwiftChocolate/p/15310960.html