如何使用QAbstractTableModel(Model/View)将数据设置到QComboBox?

How to set data to QComboBox using QAbstractTableModel (Model/View)?

我希望在使用 QAbstractTableModel 填充时能够设置 comboboxitemData。但是,我只能从模型的 data 方法中 return 一个字符串。

通常,当不使用模型时,可以这样执行:

# Set text and data
combobox.addItem('Some text', 'some item data')

# Retrieve data from selected
item_data = combobox.itemData(combobox.currentIndex())

如何做到这一点,但使用 QAbstractTableModel?


我有一个 combobox,我将其模型设置为:

model = ProjectTableModel(projects)
combobox.setModel(model)

我的模型:

class ProjectTableModel(QtCore.QAbstractTableModel):

    def __init__(self, projects=[], parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self._projects = projects

    def rowCount(self, parent):
        return len(self._projects)

    def columnCount(self, parent):
        return 2

    def data(self, index, role):
        row = index.row()
        column = index.column()

        if role == QtCore.Qt.DisplayRole and column == 0:
            project = self._projects[row]
            name = project.name()
            id = project.id()  # <----- how to add this as itemData?
            return name

A QComboBox 总是 使用模型来存储其数据。如果您不自己设置模型,它将创建自己的 QStandardItemModeladdItemitemData 等方法使用已设置的任何底层模型简单地存储和检索值。默认情况下,组合框使用 Qt.UserRole 在模型中存储项目数据。所以你的模型只需要做这样的事情:

def data(self, index, role):
    row = index.row()
    column = index.column()

    if role == QtCore.Qt.DisplayRole and column == 0:
        project = self._projects[row]
        name = project.name()
        return name
    elif role == QtCore.Qt.UserRole and column == 0:
        project = self._projects[row]
        id = project.id()
        return id

def setData(self, index, value, role):
    row = index.row()
    column = index.column()

    if role == QtCore.Qt.UserData and column == 0:
        project = self._projects[row]
        project.setId(value) # or whatever