I'm new to PyQGIS and I'm stuck here.

So I've created a ComboBox so the user could select which layer he wants to work with. Everything's fine so far. I've also added all layers but now I'm having issues to filter the output in the 2nd ComboBox.

for layer in QgsProject.instance().mapLayers().values():


So this is how I prompt all layers in my ComboBox and get the information that the user has choosen another option.

def IndexChange():
    selectedLayer = self.dlg.ComboAll.currentIndex()
    #Prompt every fields of selectedLayer in ComboLayer

And this is how I get the number of the selected layer. But I don't know what to do after that. For example, if the user choose the layer number 3 I only want fields from this layer appearing in my second ComboBox.

1 Answer 1


Below a code with a simple QDialog with 2 comboBoxes (specialized for QGIS to display layers and fields) :

class MyDialog(QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)
        self._combo_lyr = QgsMapLayerComboBox(self)
        self._combo_fld = QgsFieldComboBox(self)
        self.layout = QVBoxLayout()
        # init fields data
        # signals

    def IndexChanged(self, index):
        # see help(QgsMapLayerComboBox.layer)
        selected_layer = self._combo_lyr.layer(index)
        # see help(QgsMapLayerComboBox.layer)

md = MyDialog()


.layer(self, layerIndex: int) → QgsMapLayer

Returns the layer currently shown at the specified index within the combo box.


.setLayer(self, layer: QgsMapLayer)

Sets the layer for which fields are listed in the combobox. If no layer is set or a non-vector layer is set then the combobox will be empty.

  • Could you add some comments on this code ? I'm really beginning and I still have issues understanding some lines. Especially selected_layer = self._combo_lyr.layer(index) self._combo_fld.setLayer(selected_layer) My current objective in order to understand is to print selected layer's fields in the console. Thank you very much for your time !
    – Cinouna
    Oct 13, 2020 at 8:32
  • 1
    @NewbieCoder: I hope my post edit helps you. Oct 13, 2020 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.