【问题标题】:How to set data to QComboBox using QAbstractTableModel (Model/View)?如何使用 QAbstractTableModel(模型/视图)将数据设置为 QComboBox?
【发布时间】:2018-03-19 10:03:20
【问题描述】:

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

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

# 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

【问题讨论】:

    标签: python pyqt4 pyside pyqt5 pyside2


    【解决方案1】:

    QComboBox总是使用模型来存储其数据。如果您不自己设置模型,它将创建自己的QStandardItemModel。诸如addItemitemData 之类的方法只需使用已设置的任何底层模型来存储和检索值。默认情况下,组合框使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多