pyqt6中comboBox样式表示例
时间: 2025-07-04 11:50:13 浏览: 7
在 PyQt6 中,`QComboBox` 是一个下拉菜单控件,用户可以从其中选择一个选项。你可以通过样式表(QSS)来自定义 `QComboBox` 的外观,例如更改背景颜色、字体、边框等。
以下是使用 PyQt6 设置 `QComboBox` 样式的示例代码:
### 示例代码
```python
from PyQt6.QtWidgets import QApplication, QComboBox, QVBoxLayout, QWidget
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# 创建一个垂直布局
layout = QVBoxLayout()
# 创建 QComboBox 并添加选项
combo_box = QComboBox()
combo_box.addItems(["选项1", "选项2", "选项3"])
# 设置 QComboBox 的样式表
combo_box.setStyleSheet("""
QComboBox {
background-color: lightblue;
color: black;
font-size: 14px;
border: 1px solid gray;
border-radius: 5px;
padding: 5px;
}
QComboBox:hover {
border: 1px solid blue;
}
QComboBox::drop-down {
width: 20px;
border-left: 1px solid gray;
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
background-color: lightgray;
}
QComboBox::down-arrow {
image: url(arrow.png); /* 替换为你的箭头图片路径 */
}
QComboBox QAbstractItemView {
selection-background-color: lightgreen;
selection-color: black;
background-color: white;
border: 1px solid gray;
outline: 0px;
}
""")
# 将 QComboBox 添加到布局中
layout.addWidget(combo_box)
# 设置窗口布局
self.setLayout(layout)
# 创建应用程序实例
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
```
---
### 解释
1. **QComboBox {}**:
- 定义了 `QComboBox` 的默认样式。
- `background-color: lightblue;`: 设置背景颜色为浅蓝色。
- `color: black;`: 设置文字颜色为黑色。
- `font-size: 14px;`: 设置字体大小为 14 像素。
- `border: 1px solid gray;`: 设置边框宽度为 1 像素,样式为实线,颜色为灰色。
- `border-radius: 5px;`: 设置圆角半径为 5 像素。
- `padding: 5px;`: 设置内边距为 5 像素。
2. **QComboBox:hover {}**:
- 定义了鼠标悬停时的样式。
- `border: 1px solid blue;`: 当鼠标悬停时,边框颜色变为蓝色。
3. **QComboBox::drop-down {}**:
- 定义了下拉按钮的样式。
- `width: 20px;`: 设置下拉按钮的宽度为 20 像素。
- `border-left: 1px solid gray;`: 设置左侧边框为 1 像素宽的灰色线条。
- `background-color: lightgray;`: 设置下拉按钮的背景颜色为浅灰色。
4. **QComboBox::down-arrow {}**:
- 定义了下拉箭头的样式。
- `image: url(arrow.png);`: 使用自定义的箭头图片(需要替换为实际路径)。
5. **QComboBox QAbstractItemView {}**:
- 定义了下拉列表项的样式。
- `selection-background-color: lightgreen;`: 设置选中项的背景颜色为浅绿色。
- `selection-color: black;`: 设置选中项的文字颜色为黑色。
- `background-color: white;`: 设置下拉列表的背景颜色为白色。
- `border: 1px solid gray;`: 设置下拉列表的边框为 1 像素宽的灰色线条。
- `outline: 0px;`: 移除选中项的外边框。
---
###
阅读全文
相关推荐


















