PyQt:如何在选择项目时保持 ComboBox 打开

PyQt: How to keep ComboBox open while selecting items

遵循以下 link 提供的解决方案(效果很好):

PyQt: How to set Combobox Items be Checkable?

如何在 select 编辑项目时让 ComboBox 保持打开状态? 目前,使用提供的解决方案,在每个 select 上,列表都会崩溃...

也许最好改用 QListWidget/QListView。如果您使用每个 QListWidgetItem 或在您的自定义模型中设置可检查标志(例如使用 QStandardItemModel),那么检查标志也应该适用于此。

我建议不要使用组合框的原因:该小部件并不意味着要保持打开状态以进行多项选择;你会违反用户的期望,并且应该预料到可用性问题 ("How can I close that selection? It doesn't work like the others!")。

以下是保持列表打开的链接解决方案的修订版。单击列表外部或按 Esc.

可关闭列表
from PyQt4 import QtCore, QtGui

class CheckableComboBox(QtGui.QComboBox):
    def __init__(self, parent=None):
        super(CheckableComboBox, self).__init__(parent)
        self.view().pressed.connect(self.handleItemPressed)
        self._changed = False

    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)
        self._changed = True

    def hidePopup(self):
        if not self._changed:
            super(CheckableComboBox, self).hidePopup()
        self._changed = False

    def itemChecked(self, index):
        item = self.model().item(index, self.modelColumn())
        return item.checkState() == QtCore.Qt.Checked

    def setItemChecked(self, index, checked=True):
        item = self.model().item(index, self.modelColumn())
        if checked:
            item.setCheckState(QtCore.Qt.Checked)
        else:
            item.setCheckState(QtCore.Qt.Unchecked)

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.combo = CheckableComboBox(self)
        for index in range(6):
            self.combo.addItem('Item %d' % index)
            self.combo.setItemChecked(index, False)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.combo)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 200, 100)
    window.show()
    sys.exit(app.exec_())