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]

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()
fields = layerFields.pendingFields()
field_names = [field.name() for field in fields]
  • This code works for me. – dmh126 Jun 6 '16 at 8:54
  • Added the code for the layer combobox for clarification, I guess something is still wrong there, haven't found the problem myself yet. – Bert Jun 6 '16 at 10:03
  • Agree with @dmh126 that it also works for me. When you have the Python Console open and you load your plugin, does it report any errors? – Joseph Jun 6 '16 at 10:28
  • mMapLayerComboBox was created as QComboBox instance or QgsMapLayerComboBox? – dmh126 Jun 6 '16 at 11:35
  • It was created as a QgsMapLayerComboBox. And no, the console doesn't report any errors. – Bert Jun 6 '16 at 16:21

Use QgsFieldComboBox instead - then all the work is already done for you, including nice features like showing the field type in an icon. See https://qgis.org/api/classQgsFieldComboBox.html

  • I did use QgsFieldComboBox, should it be filled automatically? Feels like I'm missing something here ;) . – Bert Jun 6 '16 at 19:57
  • 2
    Have you set the layer associated with the box using setLayer? – ndawson Jun 6 '16 at 20:04

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.