自定义 QComboBox多选例子
时间: 2023-07-29 08:10:02 浏览: 107
以下是使用自定义 QComboBox 实现多选功能的示例代码:
```python
import sys
from PyQt5.QtCore import Qt, QRect
from PyQt5.QtGui import QPainter
from PyQt5.QtWidgets import QApplication, QComboBox
class MultiSelectComboBox(QComboBox):
def __init__(self, parent=None):
super(MultiSelectComboBox, self).__init__(parent)
self.setInsertPolicy(QComboBox.NoInsert) # 禁止用户手动输入
self.is_multi_select = False # 多选标志
self.selected_items = set() # 存储已选项的集合
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
if self.is_multi_select:
self.is_multi_select = False
else:
self.is_multi_select = True
self.showPopup() # 显示下拉选项
def paintEvent(self, event):
painter = QPainter(self)
option = self.view().itemDelegate().styleOptionViewItem()
# 绘制已选项的背景色
for index in range(self.model().rowCount()):
if index in self.selected_items:
option.rect = self.view().visualRect(index)
painter.save()
painter.fillRect(option.rect, option.palette.highlight())
painter.restore()
# 绘制文本
self.view().itemDelegate().paint(painter, option, QModelIndex())
def hidePopup(self):
if not self.is_multi_select:
super(MultiSelectComboBox, self).hidePopup()
def addItem(self, text):
super(MultiSelectComboBox, self).addItem(text)
def itemSelected(self, index):
if self.is_multi_select:
if index in self.selected_items:
self.selected_items.remove(index)
else:
self.selected_items.add(index)
else:
self.selected_items.clear()
self.selected_items.add(index)
self.update()
if __name__ == '__main__':
app = QApplication(sys.argv)
combo = MultiSelectComboBox()
combo.addItem("Option 1")
combo.addItem("Option 2")
combo.addItem("Option 3")
combo.show()
sys.exit(app.exec_())
```
在上述代码中,我们创建了一个名为 `MultiSelectComboBox` 的自定义多选下拉框类。在该类中,我们重写了 `mousePressEvent` 方法来切换多选标志,并在多选状态下显示下拉选项。我们还重写了 `paintEvent` 方法来自定义绘制已选项的样式。通过 `selected_items` 集合来存储已选项的索引。
运行上述代码,你将看到一个具有多选功能的下拉框。当你点击下拉按钮时,切换到多选状态,再次点击则切换回单选状态。在多选状态下,你可以点击并选择多个选项,已选项会以不同的背景色进行区分。
阅读全文