阅读 183

Qt setStyleSheet不生效解决办法总结

setStyleSheet不生效原因总结

1、继承自QWidget但未重写paintevent

解决方案:

参考官方文档


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

文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐