gpt4 book ai didi

python - 使用QAbstractTableModel(模型/ View )时如何将 "Select one..."添加到QComboBox?

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:43 24 4
gpt4 key购买 nike

我正在使用 QAbstractTableModel 来填充 QComboBox。这很好用,但我希望始终拥有第一个组合框索引来包含“选择一个...”的值。

这可能吗?如果可能的话,如何实现?

<小时/>

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

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:
# Set the item's text
project = self._projects[row]
name = project.name()
return name
elif role == QtCore.Qt.UserRole and column == 0:
# Set the "itemData"
project = self._projects[row]
id = project.id()
return id

最佳答案

您可以在获取/设置值时添加适当的条件,并在必要时调整行数/数量。下面的示例展示了如何执行此操作,但您应该仔细检查所有代码,以确保在访问 _projects 项时始终正确调整该行。 (请注意,在访问模型本身中的行时,您不需要调整行号)。

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) + 1 # adjust row count

def columnCount(self, parent):
return 2

def data(self, index, role):
row = index.row() - 1 # adjust row number
column = index.column()

if role == QtCore.Qt.DisplayRole and column == 0:
if row >= 0:
# Set the item's text
project = self._projects[row]
return project.name()
else:
return 'Select one...'
elif role == QtCore.Qt.UserRole and column == 0 and row >= 0:
# Set the "itemData"
project = self._projects[row]
id = project.id()
return id

def setData(self, index, value, role):
row = index.row() - 1 # adjust row number
column = index.column()

# ignore the first item in the model
if role == QtCore.Qt.DisplayRole and column == 0 and row >= 0:
project = self._projects[row]
project.setName(value) # or whatever

关于python - 使用QAbstractTableModel(模型/ View )时如何将 "Select one..."添加到QComboBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46629078/

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