Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Qt CSS样式表不应用于自定义QWidget_Qt_Widget_Qtstylesheets - Fatal编程技术网

Qt CSS样式表不应用于自定义QWidget

Qt CSS样式表不应用于自定义QWidget,qt,widget,qtstylesheets,Qt,Widget,Qtstylesheets,我想做的是将自定义CSS应用于从QLabel派生的自定义小部件,但我没有运气 我将自定义类定义为: class CustomLabel : public QLabel { } 我没有重新实现paintEvent函数,因为我认为鉴于标准QLabel支持CSS样式表,我只需要在CSS中引用这个新的小部件,例如: CustomLabel { background-color: #111111; font-size: 18px; font-weight: bold; } 不

我想做的是将自定义CSS应用于从
QLabel
派生的自定义小部件,但我没有运气

我将自定义类定义为:

class CustomLabel : public QLabel {

}
我没有重新实现
paintEvent
函数,因为我认为鉴于标准
QLabel
支持CSS样式表,我只需要在CSS中引用这个新的小部件,例如:

CustomLabel {
    background-color: #111111;
    font-size: 18px;
    font-weight: bold;
}
不幸的是,在运行时,没有应用样式
CustomLabel
,而是应用默认的
QLabel
样式

有人能告诉我为什么
CustomLabel
会忽略我的CSS规则吗

重新创建的步骤

  • 使用QtCreator创建QtWidgets项目
  • 添加从
    QLabel
    派生的自定义类,并将其称为
    CustomLabel
  • 使用设计器将
    QLabel
    添加到表单中
  • 将标签升级为
    CustomLabel
  • 使用
    main.cpp
    中的以下代码应用样式表:

    a.setStyleSheet("CustomLabel {font-weight: bold;}");
    
  • 运行该程序并注意
    CustomLabel
    的样式如何与CSS样式不一致


  • 好的,所以我设法找到了一个“变通方法”,而不是一个正确的答案:使用
    accessibleName
    参数

    因此,在Qt Creator中,为
    QLabel
    accessibleName
    字段分配一个值,例如
    CustomLabel
    ,并在CSS文件中添加以下内容:

    QLabel[accessibleName="CustomLabel"] {
        font-size: 11px;
    }
    

    您应该在
    CustomLabel
    定义中使用宏
    Q\u对象
    ,否则Qt的类型系统不知道
    CustomLabel

    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中。参考这个问题:accessibleName是QWidget的一个属性。它可以改变。不幸的是,我已经尝试过了,但没有什么不同。我添加了一个。这适用于我使用Qt5.9.Hmm,很有趣-我使用的是5.9.1,但它不适用于我。我已经完成了
    清理
    、运行
    qmake
    构建