QGIS Plugin - Automatically update field names combo box using data from another combo box
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)
Just a little update for QGIS 3 users, layers = self.iface.legendInterface().layers()
should be replaced by layers = [layer for layer in QgsProject.instance().mapLayers().values()]