CSS 样式表不适用于自定义 QWidget [英] CSS Stylesheet is not applied to custom QWidget
问题描述
我想要做的是将自定义 CSS 应用于从 QLabel
派生的自定义小部件,但我没有运气.
What I'm trying to do is to apply custom CSS to a custom widget deriving from QLabel
but I'm having no luck.
我将自定义类定义为:
class CustomLabel : public QLabel {
}
我没有重新实现 paintEvent
函数,因为我认为鉴于标准 QLabel
支持 CSS 样式表,我只需要参考这个新的小部件在 CSS 中,例如:
I've not re-implemented the paintEvent
function as I thought that given that the standard QLabel
supports CSS stylesheets, I would just need to refer to this new widget in CSS, for example:
CustomLabel {
background-color: #111111;
font-size: 18px;
font-weight: bold;
}
不幸的是,在运行时,CustomLabel
没有应用任何样式,而是应用了默认的 QLabel
样式.
Unfortunately at run-time, no style is applied the CustomLabel
and the default QLabel
style is applied.
谁能建议为什么我的 CSS 规则被 CustomLabel
忽略?
Can anyone suggest why my CSS rules are being ignored for CustomLabel
?
重新创建的步骤
- 使用 Qt Creator 创建 Qt Widgets 项目
- 添加一个从
QLabel
派生的自定义类并调用它CustomLabel
- 使用设计器将
QLabel
添加到表单上 - 将标签提升为
CustomLabel
类 使用
main.cpp
中的以下代码应用样式表:
- Create a Qt Widgets project using Qt Creator
- Add a custom class derived from
QLabel
and call itCustomLabel
- Add a
QLabel
onto a form using the designer - Promote the label to a
CustomLabel
class Apply the stylesheet using the following code in
main.cpp
:
a.setStyleSheet("CustomLabel {font-weight: bold;}");
运行程序并注意 CustomLabel
的样式如何不符合 CSS 样式.
Run the program and notice how CustomLabel
is not styled in accordance with the CSS style.
推荐答案
尝试为您的自定义标签设置 Qt::WA_StyledBackground
属性.
Try settings Qt::WA_StyledBackground
attribute for your custom label.
这篇关于CSS 样式表不适用于自定义 QWidget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!