BlueRoseNote/07-Other/Qt/QtGUI/QSS笔记.md
2023-06-29 11:55:02 +08:00

3.0 KiB
Raw Blame History

通用选择器

  • 作为选择器,作用于所有的 widget。

类型选择器 类名 作为选择器,作用于它自己和它的所有子类。

QFrame {
   background: gray;
}

类选择器

. + 类名 或者 . + class 的属性值 作为选择器(使用 setProperty(“class”, “QSSClassName”) 设置),只会作用于它自己,它的子类不受影响,注意和类型选择器的区别。

app.setStyleSheet(".QWidget { background: gray; }"
                  ".RedButton { background: magenta; }");

// .RedButton 将作为类选择器
openButton->setProperty("class",  "RedButton");
closeButton->setProperty("class", "RedButton");

ID 选择器

'#' + objectName 作为选择器,只作用于用此 objectName 的对象

// #openButton 和 #closeButton 作为 ID 选择器
app.setStyleSheet(".QWidget { background: gray; }"
                  "#openButton, #closeButton { background: magenta; }");
    
openButton->setObjectName("openButton");
closeButton->setObjectName("closeButton");

属性选择器

选择器[属性="值"] 作为选择器,这个属性可用通过 object->property(propertyName) 访问的Qt 里称为 Dynamic Properties。

如上面的程序, openButton 和 closeButton 的背景是洋红色的,但是 saveButton 不受影响,也可以使用属性选择器来实现:

app.setStyleSheet(".QWidget { background: gray; }"
                  "QPushButton[level='dangerous'] { background: magenta; }");

openButton->setProperty("level",  "dangerous");

属性选择器可以包含多个属性,只需要:

QPushButton[level='aaa'],QPushButton[level='bbb'] { background: magenta; }

如果有多个属性,则会优先选择匹配数多的样式。

包含选择器

英语叫做 Descendant Selectordescendant 的表达比较到位。

选择器之间用空格隔开,作用于 Widget 的 子Widget子Widget 的 子Widget……子子孙孙无穷尽也。

QFrame {
	background: gray;
}

/* 设置 QFrame 中的 QPushButton 的 QSS */
QFrame QPushButton {
    border: 2px solid magenta;
    border-radius: 10px;
    background: white;
    padding: 2px 15px;
}

子元素选择器

选择器之间用 > 隔开,作用于 Widget 的直接 子Widget注意和包含选择器的区别。

QFrame {
	background: gray;
}
    
QFrame > QPushButton {
    border: 2px solid magenta;
    border-radius: 10px;
    background: white;
    padding: 2px 15px;
}

伪类选择器

选择器:状态 作为选择器,支持 ! 操作符,表示 非。

QPushButton:hover { color: white }
QCheckBox:checked { color: white }
QCheckBox:!checked { color: red }

Subcontrol 选择器

选择器::subcontrol 作为选择 Subcontrol 的选择器。

有些 widget 是由多个部分组合成的,例如 QCheckBox 由 icon(indicator) 和 text 组成,可以使用 选择器::subcontrol 来设置 subcontrol 的样式:

QCheckBox::indicator {
    width: 20px;
    height: 20px;
}

QCheckBox {
    spacing: 8px;
}