5

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():
    self.dlg.ComboAll.addItem(layer.name())

self.dlg.ComboAll.currentIndexChanged.connect(IndexChange)

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.

8

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()
        self.setLayout(self.layout)
        self.layout.addWidget(self._combo_lyr)
        self.layout.addWidget(self._combo_fld)
        # init fields data
        self.IndexChanged(0)
        # signals
        self._combo_lyr.currentIndexChanged.connect(self.IndexChanged)

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

md = MyDialog()
md.show()

QgsMapLayerComboBox

.layer(self, layerIndex: int) → QgsMapLayer

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

QgsFieldComboBox

.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.

2
  • 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 '20 at 8:32
  • 1
    @NewbieCoder: I hope my post edit helps you. Oct 13 '20 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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