1 回答
TA贡献1875条经验 获得超3个赞
checkedItems 方法不存在,因此您会收到该错误。解决方案是迭代模型并验证它是否被检查。
from PyQt5 import QtCore, QtGui, QtWidgets
class CheckableComboBox(QtWidgets.QComboBox):
closedPopup = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(CheckableComboBox, self).__init__(parent)
self.setView(QtWidgets.QListView(self))
self.view().pressed.connect(self.handleItemPressed)
self.setModel(QtGui.QStandardItemModel(self))
firstItem = QtGui.QStandardItem("Select Years")
firstItem.setBackground(QtGui.QBrush(QtGui.QColor(200, 200, 200)))
firstItem.setSelectable(False)
self.model().appendRow(firstItem)
@QtCore.pyqtSlot(QtCore.QModelIndex)
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)
def checkedItems(self):
l = []
for i in range(self.model().rowCount()):
it = self.model().item(i)
if it.checkState() == QtCore.Qt.Checked:
l.append(it.text())
return l
def hidePopup(self):
self.closedPopup.emit()
super(CheckableComboBox, self).hidePopup()
QtCore.QTimer.singleShot(0, lambda: self.setCurrentIndex(0))
class Dialog_01(QtWidgets.QMainWindow):
def __init__(self):
super(Dialog_01,self).__init__()
years = ["2017", "2018", "2019", "2020"]
self.comboBoxv = CheckableComboBox()
self.comboBoxv.closedPopup.connect(self.on_closedPopup)
for i, area in enumerate(years):
item = QtGui.QStandardItem(area)
item.setCheckable(True)
item.setCheckState(QtCore.Qt.Unchecked)
self.comboBoxv.model().appendRow(item)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QVBoxLayout(central_widget)
lay.addWidget(self.comboBoxv)
lay.addStretch()
@QtCore.pyqtSlot()
def on_closedPopup(self):
print(self.comboBoxv.checkedItems())
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
添加回答
举报