本文主要是介绍PyQt5 QComboBox中添加带CheckBox的选项,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
效果
代码
"""
可多选的下拉框
通过CheckableComboBox.texts_list 可以获取选中的item值组成的列表;用CheckableComboBox.currentText没法显示全texts_list = [] # 所有选中的item文本组成的列表
item_list = [] # 所有选中的item组成的列表
"""from PyQt5.QtCore import Qt, QEvent
from PyQt5.QtGui import QStandardItem, QFontMetrics, QPalette
from PyQt5.QtWidgets import QStyledItemDelegate, QComboBox, qAppclass CheckableComboBox(QComboBox):# Subclass Delegate to increase item heightclass Delegate(QStyledItemDelegate):def sizeHint(self, option, index):size = super().sizeHint(option, index)size.setHeight(20)return sizedef __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)self.texts_list = [] # 所有选中的item文本组成的列表self.item_list = [] # 所有选中的item组成的列表# Make the combo editable to set a custom text, but readonlyself.setEditable(True)self.lineEdit().setReadOnly(True)# Make the lineedit the same color as QPushButtonpalette = qApp.palette()palette.setBrush(QPalette.Base, palette.button())self.lineEdit().setPalette(palette)# Use custom delegateself.setItemDelegate(CheckableComboBox.Delegate())# Update the text when an item is toggledself.model().dataChanged.connect(self.updateText)# Hide and show popup when clicking the line editself.lineEdit().installEventFilter(self)self.closeOnLineEditClick = False# Prevent popup from closing when clicking on an itemself.view().viewport().installEventFilter(self)def resizeEvent(self, event):# Recompute text to elide as neededself.updateText()super().resizeEvent(event)def eventFilter(self, object, event):if object == self.lineEdit():if event.type() == QEvent.MouseButtonRelease:if self.closeOnLineEditClick:self.hidePopup()else:self.showPopup()return Truereturn Falseif object == self.view().viewport():if event.type() == QEvent.MouseButtonRelease:index = self.view().indexAt(event.pos())item = self.model().item(index.row())if item.checkState() == Qt.Checked:item.setCheckState(Qt.Unchecked)else:item.setCheckState(Qt.Checked)return Truereturn Falsedef showPopup(self):super().showPopup()# When the popup is displayed, a click on the lineedit should close itself.closeOnLineEditClick = Truedef hidePopup(self):super().hidePopup()# Used to prevent immediate reopening when clicking on the lineEditself.startTimer(100)# Refresh the display text when closingself.updateText()def timerEvent(self, event):# After timeout, kill timer, and reenable click on line editself.killTimer(event.timerId())self.closeOnLineEditClick = Falsedef updateText(self):self.texts_list = []self.item_list = []for i in range(self.model().rowCount()):if self.model().item(i).checkState() == Qt.Checked:self.texts_list.append(self.model().item(i).text())self.item_list.append(self.model().item(i))text = ", ".join(self.texts_list)# Compute elided text (with "...")metrics = QFontMetrics(self.lineEdit().font())elidedText = metrics.elidedText(text, Qt.ElideRight, self.lineEdit().width())self.lineEdit().setText(elidedText)def addItem(self, text, data=None):item = QStandardItem()item.setText(text)if data is None:item.setData(text)else:item.setData(data)item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)item.setData(Qt.Unchecked, Qt.CheckStateRole)self.model().appendRow(item)# self.model().item(0).setCheckState(Qt.Checked) # 将第一个item设置为选中状态def addItems(self, texts, datalist=None):for i, text in enumerate(texts):try:data = datalist[i]except (TypeError, IndexError):data = Noneself.addItem(text, data)def currentData(self):# Return the list of selected items datares = []for i in range(self.model().rowCount()):if self.model().item(i).checkState() == Qt.Checked:res.append(self.model().item(i).data())return resif __name__ == '__main__':from PyQt5 import QtWidgets,QtCoreimport syscomunes = ['Ameglia', 'Arcola', 'Bagnone', 'Bolano', 'Carrara', 'Casola', 'Castelnuovo Magra','Comano, località Crespiano', 'Fivizzano', 'Fivizzano località Pieve S. Paolo','Fivizzano località Pieve di Viano', 'Fivizzano località Soliera', 'Fosdinovo', 'Genova','La Spezia', 'Levanto', 'Licciana Nardi', 'Lucca', 'Lusuolo', 'Massa', 'Minucciano','Montignoso', 'Ortonovo', 'Piazza al sercho', 'Pietrasanta', 'Pignine', 'Pisa','Podenzana', 'Pontremoli', 'Portovenere', 'Santo Stefano di Magra', 'Sarzana','Serravezza', 'Sesta Godano', 'Varese Ligure', 'Vezzano Ligure', 'Zignago']app = QtWidgets.QApplication(sys.argv)Form = QtWidgets.QWidget()comboBox1 = CheckableComboBox(Form)comboBox1.addItems(comunes)Form.show()sys.exit(app.exec_())
这篇关于PyQt5 QComboBox中添加带CheckBox的选项的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!