使用 QAbstractTableModel(模型/视图)时如何将“选择一个...”添加到 QComboBox?
Posted
技术标签:
【中文标题】使用 QAbstractTableModel(模型/视图)时如何将“选择一个...”添加到 QComboBox?【英文标题】:How to add "Select one..." to QComboBox when using QAbstractTableModel (Model/View)? 【发布时间】:2017-10-08 08:34:07 【问题描述】:我正在使用QAbstractTableModel
来填充QComboBox
。这很好用,但我希望始终让第一个组合框索引包含“选择一个...”的值。
这可能吗?如果可以,怎么做?
我有一个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:
# 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
【问题讨论】:
【参考方案1】:您可以在获取/设置值时添加适当的条件,并在必要时调整行数/行数。下面的示例显示了如何执行此操作,但您应该仔细检查所有代码,以确保在访问 _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
【讨论】:
以上是关于使用 QAbstractTableModel(模型/视图)时如何将“选择一个...”添加到 QComboBox?的主要内容,如果未能解决你的问题,请参考以下文章
从 QAbstractTableModel 类中访问视图和代理模型?
带有 qTableview 的 Pandas 模型的慢 PyQt5 QAbstractTableModel
Qt入门教程数据模型篇 QAbstractTableModel抽象表格模型