gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:40:42 25 4
gpt4 key购买 nike

当使用 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


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

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总是使用模型来存储它的数据。如果您不自己设置模型,它将创建自己的 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

关于python - 如何使用 QAbstractTableModel(模型/ View )将数据设置到 QComboBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46625371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com