2017-10-08 56 views
1

我使用的是QAbstractTableModel来填充QComboBox。这很好,但我希望总是有第一个组合框索引包含“Select one ...”的值。如何在使用QAbstractTableModel(模型/视图)时将“Select one ...”添加到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 
相关问题