CSS样式表不适用于自定义QWidget
我想要做的是将自定义CSS应用于从QLabel
派生的自定义小部件,但我没有运气。CSS样式表不适用于自定义QWidget
我已经定义了自定义类为:
class CustomLabel : public QLabel {
}
我没有重新实现的paintEvent
功能,因为我认为,鉴于该标准QLabel
支持CSS样式表,我只需要参考此在CSS新的小工具,例如:
CustomLabel {
background-color: #111111;
font-size: 18px;
font-weight: bold;
}
不幸的是,在运行时,没有风格应用CustomLabel
和应用默认QLabel
风格。
任何人都可以提出为什么我的CSS规则被忽略为CustomLabel
?
步骤重新创建
- 使用Qt Creator的
- 添加派生的自定义类从
QLabel
,并调用它CustomLabel
- 添加
QLabel
到窗体使用设计 创建Qt控件项目
- 将标签升级为
CustomLabel
类 -
应用使用下面的代码样式表中
main.cpp
:a.setStyleSheet("CustomLabel {font-weight: bold;}");
运行程序,并注意如何
CustomLabel
不按照CSS样式风格。
好了,我已经成功地找到一个“解决办法”,而不是一个合适的回答:使用accessibleName
参数。
所以在Qt Creator中,分配一个值,如CustomLabel
到QLabel
的accessibleName
领域,并在CSS文件中,添加以下内容:
QLabel[accessibleName="CustomLabel"] {
font-size: 11px;
}
accessibleName是QWidget的一个属性。它可以改变。 http://doc.qt.io/qt-5/qwidget.html#accessibleName-prop –
你应该使用宏Q_OBJECT
您CustomLabel
定义中,否则CustomLabel
不知道Qt的类型系统:
class CustomLabel : public QLabel {
Q_OBJECT
}
MCVE
CustomLabel.h:
#include "QLabel"
class CustomLabel : public QLabel {
Q_OBJECT
};
main.cpp中:
#include "QApplication"
#include "CustomLabel.h"
int main(int argc, char * argv[])
{
QApplication a(argc, argv);
a.setStyleSheet("CustomLabel {font-weight: bold; background-color: red;}");
CustomLabel label;
label.setText ("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua");
label.show();
a.exec();
}
尝试设置Qt::WA_StyledBackground
属性自定义标签。
如果您的CustomLabel具有名称空间,则需要将该名称空间添加到您的css中。请参阅此问题:https://stackoverflow.com/questions/26206492/qt-stylesheet-in-derived-class-in-c-namespace-selector –