QGIS Plugin – How to Automatically Update Field Names Combo Box Using Data from Another Combo Box

pyqgisqgisqgis-plugins

I am creating my very first QGIS plugin using two combo boxes – one to select a layer and the other to select a field.

Whilst the layer selection feature seems to work, the field name combo box is not updated when a new layer is selected.

My code is as follows…

    self.dlg.comboBox.clear()
    self.dlg.comboBox_2.clear()

    layers = self.iface.legendInterface().layers()
    layer_list = []
    for layer in layers:
        layer_list.append(layer.name())
    self.dlg.comboBox.addItems(layer_list)
    selectedLayerIndex = self.dlg.comboBox.currentIndex()
    selectedLayer = layers[selectedLayerIndex]

    fields = [field.name() for field in selectedLayer.pendingFields() ]
    self.dlg.comboBox_2.addItems(fields)

Does anyone happen to know how I can accomplish this?

Best Answer

You could put most of your code in a function which will be run every time a user changes the current layer from the combobox. For example, you could use something like:

self.dlg.comboBox.clear()
self.dlg.comboBox_2.clear()

layers = self.iface.legendInterface().layers()
layer_list = []
for layer in layers:
    layer_list.append(layer.name())
self.dlg.comboBox.addItems(layer_list)

def field_select():
    self.dlg.comboBox_2.clear()
    selectedLayerIndex = self.dlg.comboBox.currentIndex()
    selectedLayer = layers[selectedLayerIndex]
    fields = [field.name() for field in selectedLayer.pendingFields()]
    self.dlg.comboBox_2.addItems(fields)

# This connects the function to the layer combobox when changed
self.dlg.comboBox.currentIndexChanged.connect(field_select)
Related Question