---
title: "PyQt开发-QSS 选择器语法指南"
author: "Perrin Yong"
author_profile: https://www.pystone.net/profile/
published_by: "Perrin Yong"
canonical: https://www.pystone.net/notes/pyqt-qss-selector-syntax/
type: note
content_role: unspecified
visibility: public
id_stability: rename-stable
source_path: "10-计算机、信息技术与工程/04-应用开发与云端工程/桌面应用开发/PyQt开发-QSS 选择器语法指南.md"
content_hash: 45b8c69ae21962a7d675c3a378e5f0649ad3ed467109bf2ff7cb1d488416895b
knowledge_version: 224c990773de.5fa8af6e39fa
site_commit: 224c990773de166d23a886306577dd90379529ce
notes_commit: 5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a
---
![assets/image-20250212222619282.png](/media/b36d600fc746b2706835.png)


# PyQt开发-QSS 选择器语法指南
## 1. 选择器概述

QSS 选择器用于选择一个或多个需要应用样式的 Qt 部件。详细文档可参考：[Qt 官方 QSS 语法文档](https://doc.qt.io/qt-5/stylesheet-syntax.html)

## 2. 选择器类型

### 2.1 类型（Type）选择器

```css
QFrame {
   background: gray;
}
```

作用于所有 `QFrame` 控件。

### 2.2 类（Class）选择器

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

```python

#include <QApplication>
#include <QPushButton>
#include <QHBoxLayout>
int main(int argc, char *argv[]) {
	QApplication app(argc, argv);
	app.setStyleSheet("QWidget { background: gray; }");
	QWidget *window = new QWidget();
	QPushButton *openButton = new QPushButton("打开", window);
	QPushButton *closeButton = new QPushButton("关闭", window);
	QPushButton *saveButton = new QPushButton("保存", window);
	QHBoxLayout *layout = new QHBoxLayout(window);
	layout->addWidget(openButton);
	layout->addWidget(closeButton);
	layout->addWidget(saveButton);
	window->setLayout(layout);
	window->show();
	return app.exec();

}

```

如果只想要 window 的背景是灰色的，按钮的背景不变，可以使用类选择器 `.QWidget`

```python
## 把 QWidget 改成 .QWidget
app.setStyleSheet(".QWidget {background: gray;}")
```

设置某个组件的类名

```python
app.setStyleSheet(".QWidget { background: gray; }"
".RedButton { background: magenta; }");
## .RedButton 将作为类选择器
openButton->setProperty("class", "RedButton");
closeButton->setProperty("class", "RedButton");
```

### 2.3 ID（ObjectName）选择器

`# + objectName` 作为选择器，仅作用于指定 objectName 的对象。

```python
app.setStyleSheet(".QWidget { background: gray; }"
                  "#openButton, #closeButton { background: magenta; }");

openButton->setObjectName("openButton");
closeButton->setObjectName("closeButton");
```

### 2.4 属性（Property）选择器

基于动态属性匹配元素：

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

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

### 2.5 包含（Descendant）选择器

用于选择某个 Widget 的所有子 Widget：

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

### 2.6 子元素（Child）选择器

仅作用于 Widget 的直接子 Widget：

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

### 2.7 伪类选择器

基于组件状态匹配：

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

### 2.8 Subcontrol 选择器

某些 Widget 由多个部分组成，例如 `QCheckBox` 包含 `indicator` 和 `text`，可使用 `选择器::subcontrol` 设置样式。

|Subcontrol|说明|
|---|---|
|`::indicator`|适用于 `QCheckBox`、`QRadioButton`、`QMenuItem` 等的指示器|
|`::menu-indicator`|`QPushButton` 的菜单指示器|
|`::up-button`|`QSpinBox` 或 `QScrollBar` 的上按钮|
|`::down-button`|`QSpinBox` 或 `QScrollBar` 的下按钮|
|`::drop-down`|`QComboBox` 的下拉箭头|
|`::title`|`QGroupBox` 或 `QDockWidget` 的标题|
|`::chunk`|`QProgressBar` 进度条的块|

## 3. QSS 在工程中的用法

### 3.1 代码动态设置 QSS

#### **全局 QSS 设置**

```python
if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = MainWindow()
    styleFile = './qss/style.qss'

    with open(styleFile, 'r') as f:
        style = f.read()
        mainWindow.setStyleSheet(style)
    mainWindow.show()
    sys.exit(app.exec_())
```

#### **局部 QSS 设置**

```python
btn1.setStyleSheet('''
    QPushButton{
        color:red;
    }
    QPushButton:hover{
        background-color: green;
    }
''')

label3.setStyleSheet('background-color:yellow;font-size:30px;')
```

### 3.2 使用 Qt Designer 编写 QSS

可在 Qt Designer 的 **属性编辑器** 中直接编辑 QSS 文件，使界面风格可视化调整。
![assets/image-20240202125015625.png](/media/26ad8ecf72e4d7fb089b.png)


## 4. QSS 美化素材与工具

- **[Qt-Material](https://qt-material.readthedocs.io/en/latest/index.html#qt-material)**：适用于 PySide6、PySide2 和 PyQt5 的 Material Design 主题样式表。
- **[QDarkStyleSheet](https://github.com/ColinDuquesnoy/QDarkStyleSheet)**：提供现代化的黑暗风格 QSS。
- **[PyQt5 Stylesheets](https://github.com/RedFalsh/PyQt5_stylesheets)**：多个 PyQt5 风格样式表集合。


以上是 QSS 选择器的语法和工程实践，希望能帮助你更好地进行 Qt 界面美化和开发！```
