为什么布尔值在 QAbstractTableModel 中创建下拉菜单?

Why do boolean values create a dropdown menu in QAbstractTableModel?

在我的自定义模型设置中,布尔值会自动创建一个带有 True/False 选项的 combobox/dropdown 菜单,而字符串值会创建一个常规的行编辑类型的编辑器。

我想了解这是为什么?我可以从委托访问该编辑器以连接其信号(即 currentIndexChanged)吗?

截图

这里有一段简单的代码可以重现:

from PySide2 import QtCore, QtGui, QtWidgets
import sys

class BoolModel(QtCore.QAbstractTableModel):
    def __init__(self, parent=None):
        super(BoolModel, self).__init__(parent)
        self.bool_value = True

    def flags(self, index):
        return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled

    def rowCount(self, parent=QtCore.QModelIndex()):
        return 5

    def columnCount(self, parent=QtCore.QModelIndex()):
        return 1

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
            return self.bool_value

    def setData(self, index, value, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.EditRole:
            self.bool_value = value
            return True
        return False

app = QtWidgets.QApplication([])
model = BoolModel()
table = QtWidgets.QTableView()
table.show()
table.setModel(model)
sys.exit(app.exec_())

QItemEditorFactory is a class that allows setting an editor type for each type of data as shown in the docs:

Standard Editing Widgets
The standard factory implementation provides editors for a variety of data types. These are created whenever a delegate needs to provide an editor for data supplied by a model. The following table shows the relationship between types and the standard editors provided.

正如您所见,在布尔值的情况下,QComboBox 用作编辑器,在 QString 的情况下(或在 python 的情况下为字符串),使用 QLineEdit。

您还可以使用委托访问该编辑器:

class StyledItemDelegate(QtWidgets.QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        editor = super(StyledItemDelegate, self).createEditor(parent, option, index)
        if isinstance(editor, QtWidgets.QComboBox):
            editor.currentIndexChanged.connect(print)
        return editor
table.setItemDelegate(StyledItemDelegate(table))