如何在使用QAbstractTableModel(Model / View)时向QComboBox添加“Select one ...”?

时间:2017-10-08 08:34:07

标签: python pyqt4 pyside pyqt5 pyside2

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

这是可能的,如果是的话 - 怎么样?

我有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 个答案:

答案 0 :(得分: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