如何使用 QAbstractTableModel(模型/视图)将数据设置到 QComboBox? [英] How to set data to QComboBox using QAbstractTableModel (Model/View)?

查看:37
本文介绍了如何使用 QAbstractTableModel(模型/视图)将数据设置到 QComboBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wish to be able to set the itemData of a combobox when populated using a QAbstractTableModel. However, I can only return one string from the model's data method.

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

Usually, when not using a model, this can be performed like so:

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

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

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

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

I have a combobox, which I set a model to:

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.addItemitemData 等方法只需使用已设置的任何底层模型来存储和检索值.默认情况下,组合框使用 Qt.UserRole 在模型中存储项目数据.所以你的模型只需要做这样的事情:

A QComboBox always uses a model to store its data. If you don't set a model yourself, it will create its own QStandardItemModel. Methods such as addItem and itemData simply store and retrieve values using whatever underlying model has been set. By default, the combo-box uses the Qt.UserRole to store item-data in the model. So your model just needs to do something like this:

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

这篇关于如何使用 QAbstractTableModel(模型/视图)将数据设置到 QComboBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆