Skip to main content
 首页 » 编程设计

python之如何使用 QAbstractTableModel(模型/ View )将数据设置到 QComboBox

2024年10月01日7TianFang

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

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

# Set text and data 
combobox.addItem('Some text', 'some item data') 
 
# Retrieve data from selected 
item_data = combobox.itemData(combobox.currentIndex()) 

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


我有一个组合框,我将其模型设置为:

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 

请您参考如下方法:

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