How To Add "select One..." To Qcombobox When Using Qabstracttablemodel (model/view)?
I'm using a QAbstractTableModel to populate a QComboBox. This works great, but I wish to always have the very first combobox index to contain a value of 'Select one...'. Is this po
Solution 1:
You can add an appropriate condition when getting/setting values and adjust the row count/number where necessary. The example below shows how to do this, but you should check all your code carefully to make sure the row is always adjusted properly when accessing the _projects
items. (And note that you don't need to to adjust the row number when accessing rows in the model itself).
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
Post a Comment for "How To Add "select One..." To Qcombobox When Using Qabstracttablemodel (model/view)?"