pythonpyqt5qcombobox

How can I get the model index from Qcombobox


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


Solution

  • 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:

        def getModelIndex(self, index, combo):
            model = combo.model()
            item = model.item(index)
            modelIndex = model.indexFromItem()
    

    Note that the above is only valid if the following requirements are met:

    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:

        def getModelIndex(self, index, combo):
            modelIndex = combo.model().index(
                index, combo.modelColumn(), combo.rootIndex())
    

    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 ItemDataRole enum, you can just use the itemData() function:

        def getComboData(self, index):
            data = combo.itemData(index, SomeRole)
    

    Just remember that the itemData() implementation uses Qt.UserRole as default role, so you need to explicitly use the correct role, and you will always get what the data() function of that model returns.

    For instance, if you added an item that actually and only has a value set as a DisplayRole used with an integer (with item.setData(intValue, Qt.DisplayRole) or comboItem.setItemData(index, intValue, Qt.DisplayRole)), then the value of itemData(index) will not be the same as itemData(index, Qt.DisplayRole), nor that of itemText(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.