我能够使用 QComboBox 和 QStandardItemModel 实现多选,但我无法使用 selectedItems() 或 checkedItems() 选项获取所选项目,该选项给出的错误消息显示为:
AttributeError: 'QComboBox' object has no attribute 'selectedItems'
AttributeError: 'QComboBox' object has no attribute 'checkedItems'
有没有办法获取 QComboBox 的选定项目列表?下面是我的代码的示例实现
class CheckableComboBox(QComboBox):
def __init__(self):
super(CheckableComboBox, self).__init__()
self.view().pressed.connect(self.handleItemPressed)
self.setModel(QtGui.QStandardItemModel(self))
def handleItemPressed(self, index):
item = self.model().itemFromIndex(index)
if item.checkState() == QtCore.Qt.Checked:
item.setCheckState(QtCore.Qt.Unchecked)
else:
item.setCheckState(QtCore.Qt.Checked)
class Dialog_01(QMainWindow):
def __init__(self):
super(QMainWindow,self).__init__()
years = ["2017", "2018", "2019", "2020"]
self.comboBoxv = QComboBox(self)
self.model = QtGui.QStandardItemModel(self)
firstItem = QtGui.QStandardItem("Select Years")
firstItem.setBackground(QtGui.QBrush(QtGui.QColor(200, 200, 200)))
firstItem.setSelectable(False)
self.model.setItem(0, 0, firstItem)
for i,area in enumerate(years):
item = QtGui.QStandardItem(area)
item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
item.setData(Qt.Unchecked, Qt.CheckStateRole)
self.model.setItem(i+1, 0, item)
self.comboBoxv.setModel(self.model)
self.comboBoxv.installEventFilter(self)
if __name__ == '__main__':
app = QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
翻过高山走不出你
相关分类