• 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);
    
  • 相关阅读:
    2019-2020-20191201《信息安全专业导论》第4周学习总结
    2019-2020-20191201《信息安全专业导论》第3周学习总结
    2019-2020-191201《信息安全专业导论》第二周学习总结
    计算机概论速读提问
    自我介绍
    20191302第六章学习笔记
    20191302反汇编测试
    20191302mystat
    20191302 第五章学习
    20191302 第四章学习笔记
  • 原文地址:https://www.cnblogs.com/SwiftChocolate/p/15310960.html
Copyright © 2020-2023  润新知