使用 PyQt 的组合框中的复选框 [英] Checkboxes in a Combobox using PyQt
问题描述
我需要实现一个包含复选框的下拉列表,就像将组合框中的条目设为复选框一样.但是 QComboBox 不接受 QCheckBox 作为其成员,我找不到任何替代解决方案.我在 Qt Wiki 上在 C++ 中找到了一个实现,但不知道如何将其移植到 python.
I need to implement a drop down list that contains CheckBoxes, much like having the entries in a ComboBox being CheckBoxes. But QComboBox doesn't accept QCheckBox as its member and I couldn't find any alternate solution. I found an implementation in C++ on the Qt Wiki, but don't know how to port it to python.
推荐答案
使用组合框项目模型,因为项目支持复选框您只需要将项目标记为可供用户检查,并设置初始 checkState 以使复选框出现(它仅在存在有效状态时才显示)
Use the Combobox item model, since items support checkBoxes you just need to mark the item to be checkable by the user, and set an initial checkState to make the checkBox appear (it does only show if there is a valid state)
item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
item.setCheckState(QtCore.Qt.Unchecked) # causes checkBox to show
这是一个最小的子类示例:
Here is a minimal subclass example:
from PyQt5 import QtGui, QtCore, QtWidgets
import sys, os
# subclass
class CheckableComboBox(QtWidgets.QComboBox):
# once there is a checkState set, it is rendered
# here we assume default Unchecked
def addItem(self, item):
super(CheckableComboBox, self).addItem(item)
item = self.model().item(self.count()-1,0)
item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
item.setCheckState(QtCore.Qt.Unchecked)
def itemChecked(self, index):
item = self.model().item(i,0)
return item.checkState() == QtCore.Qt.Checked
# the basic main()
app = QtWidgets.QApplication(sys.argv)
dialog = QtWidgets.QMainWindow()
mainWidget = QtWidgets.QWidget()
dialog.setCentralWidget(mainWidget)
ComboBox = CheckableComboBox(mainWidget)
for i in range(6):
ComboBox.addItem("Combobox Item " + str(i))
dialog.show()
sys.exit(app.exec_())
这篇关于使用 PyQt 的组合框中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!