I am new to python and I am trying to write my first plugin for QGIS. Earlier I asked this question to find out how I could populate a combobox with point vector layers (and nothing else).
I've been trying to retrieve the fields of the layers and use them to populate a combobox as well. A couple hours of searching and trying have resulted in the code below. Unfortunately the combobox remains empty even though I am able to get the field names with the code below in the python console in QGIS.
#Fill combobox with vector layer fields.
layerFields = self.dlg.mMapLayerComboBox.currentLayer()
fields = layerFields.pendingFields()
field_names = [field.name() for field in fields]
self.dlg.mFieldComboBox.addItems(field_names)
Code for layer combobox:
layers = QgsMapLayerRegistry.instance().mapLayers().values()
for layer in layers:
self.dlg.mMapLayerComboBox.addItem(layer.name(), layer)
Answer: my code lacked the setLayer line. Now resulting in the code below:
layerFields = self.dlg.mMapLayerComboBox.currentLayer()
self.dlg.mFieldComboBox.setLayer(layer)
fields = layerFields.pendingFields()
field_names = [field.name() for field in fields]
self.dlg.mFieldComboBox.addItems(field_names)
mMapLayerComboBox
was created asQComboBox
instance orQgsMapLayerComboBox
?