1

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)
5
  • This code works for me.
    – dmh126
    Commented Jun 6, 2016 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
    Commented Jun 6, 2016 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
    Commented Jun 6, 2016 at 10:28
  • mMapLayerComboBox was created as QComboBox instance or QgsMapLayerComboBox?
    – dmh126
    Commented Jun 6, 2016 at 11:35
  • It was created as a QgsMapLayerComboBox. And no, the console doesn't report any errors.
    – Bert
    Commented Jun 6, 2016 at 16:21

1 Answer 1

2

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.