I fill a Qcombobox with using setModel method:
def fill_cbo(self, list, cboBox):
d = tuple(list)
print(d)
model = QtGui.QStandardItemModel()
for id_, value in d:
it = QtGui.QStandardItem(value)
it.setData(id_, IdRole)
model.appendRow(it)
if cboBox == 'casesCbo':
self.casesCbo.setModel(model)
later in the program I want to access the model index when a user selects an item in the combobox. The problem is I can't access the model directly anymore and casesCbo.CurrentIndex() just gives me the index based on an integer. How do I access the model index or more specifically the first item from the tuple?
I tried casesCbo.item(Data()) and it isnt working
QComboBox is fundamentally a mono dimensional view widget, so, the
currentIndex()function returns the selected index of the shown list, which is the "row" number in the visible popup, similarly to an index of a basic Python list or tuple.If you want the QModelIndex, you need to access the combo model:
Note that the above is only valid if the following requirements are met:
modelColumnproperty of QComboBox;A more appropriate syntax of the above, then, should be the following, which would work for any properly implemented model, and for any situation, including using different column and root index of the model within the combo:
The above syntax just follows the basic
index()implementation of any Qt model.Note that if you only need access to model data and the model properly implements the
ItemDataRoleenum, you can just use theitemData()function:Just remember that the
itemData()implementation usesQt.UserRoleas default role, so you need to explicitly use the correct role, and you will always get what thedata()function of that model returns.For instance, if you added an item that actually and only has a value set as a
DisplayRoleused with an integer (withitem.setData(intValue, Qt.DisplayRole)orcomboItem.setItemData(index, intValue, Qt.DisplayRole)), then the value ofitemData(index)will not be the same asitemData(index, Qt.DisplayRole), nor that ofitemText(index)(which always returns a string representation of that combo index).Please carefully check the QComboBox documentation in order to better understand all its underlying aspects.