【问题标题】:How to apply StyleSheet to childrens of same type than parent excluding the parent?如何将 StyleSheet 应用于与父级相同类型的子级,不包括父级?
【发布时间】:2022-11-11 02:13:24
【问题描述】:

我有一个QWidget 包含一些按钮和其他QWidgets,我如何制作应用于QWidget 的样式表父母影响只要她的QWidget 孩子?

我尝试过的一些选项:

QWidget[objectName!="widget_1"] {
     max-width: 200;
     max-height: 200;
}

QWidget > QWidget {
     max-width: 200;
     max-height: 200;
}

QWidget  QWidget {
     max-width: 200;
     max-height: 200;
}

在所有选项中,样式也适用于父级。

我正在阅读选择器类型:https://doc.qt.io/qt-6/stylesheet-syntax.html#selector-types

但我仍然不知道该怎么做。

【问题讨论】:

  • 阅读文档中的这一行:“除了 =,您还可以使用 ~= 来测试 QStringList 类型的 Qt 属性是否包含给定的 QString。” doc.qt.io/qt-6/stylesheet-syntax.html#selector-types 即所以你可能不应该使用“!=”,而是使用“~=”。
  • @HiFile.app-best 文件管理器我尝试使用“~=”,但它仍然适用于孩子。
  • 我知道您想将其应用于父母但对孩子有影响。我现在很困惑。

标签: c++ qt


【解决方案1】:

例如,如果您有这样的 UI:

您可以使用#ObjectName 设置特定对象的样式。 像这样:

QPushButton#pb_1,#pb_2  {
     min-width: 100;
     min-height:100;
    background-color: rgb(115, 210, 22);
}
QWidget #widget_1
{
    background-color: rgb(252, 233, 79);
}
QWidget#widget_1,#widget_2
{
border:2px solid red;
}

这是结果:

您也可以为特定按钮添加小部件样式,因为 QPushButton 继承自 QWidget

喜欢

QWidget#widget_1,#widget_2,#pb_1
{
border:2px solid red;
}

您也可以全部添加样式QWidgets,然后通过调用其名称来调用其父级,并为父级设置不同的样式,如下所示:

QWidget {
     border:2px solid red;
}
QWidget#centralwidget {
     border-style:none;
}

【讨论】:

    【解决方案2】:

    为您的父小部件指定对象名称并设置样式表,如下所示:

    #parentWidget QWidget { 
        /* your styles */
    }
    

    此样式表匹配QWidget 的所有实例,这些实例是QObject 的后代(子代、孙代等),对象名称为parentWidget。您还可以在“#parentWidget”之前指定小部件的类。请注意,几乎所有小部件都继承自 QWidget 类。因此样式也将应用于它们。

    如果要将样式设置为直接子级,请使用以下命令:

    #parentWidget > QWidget { 
        /* your styles */
    }
    

    如果您只想 QWidgets 获取样式(不包括继承),请使用:

    /* for all descendants */
    #parentWidget .QWidget { 
        /* your styles */
    }
    /* for all direct children */
    #parentWidget > .QWidget { 
        /* your styles */
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 2019-01-17
      相关资源
      最近更新 更多