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);
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞