I'm new to pyqgis and I'm tryig to make a combobox with list of fields (from layer also selected in combobox).

    layers = self.iface.legendInterface().layers()
    layer_list = []
    for layer in layers:

    selectedLayerIndex = self.dlg.comboBox.currentIndex()
    selectedLayer = layers[selectedLayerIndex]
    fields = selectedLayer.pendingFields()
    fieldnames = [field.name() for field in fields]

The problem is, that in second combobox there are fields from first on layerlist layer, not the selected one.


Basically, you have to use signals to detect the "change layer" event and update your field combobox accordingly. Here is a simplified example (assuming you already have the run and initGui methods defined):

In run(self):

layers = QgsMapLayerRegistry.instance().mapLayers().values() # Create list with all layers
# layers = self.iface.legendInterface().layers() might also work
for layer in layers:
    self.dlg.layerComboBox.addItem( layer.name(), layer )

Then, connect the "layer changed" event to a new onLayerChange method, in initGui(self):

self.dlg.layerComboBox.activated.connect( self.onLayerChange )

Then you have to define the onLayerChange(self) method:

def onLayerChange(self, index):

    self.dlg.attributeComboBox.clear() # clears the combobox
    layer = self.dlg.layerComboBox.itemData( index ) # gets selected layer
    for field in layer.pendingFields():
        self.dlg.attributeComboBox.addItem( field.name(), field ) # lists layer fields

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.