I recommend very strongly to consider using a custom QGIS widget for your layer combo box. Instead of a generic
QComboBox, you can use a
QgsMapLayerComboBox. This custom widget will load automatically all layers loaded in the current project, however you can easily filter these to only show polygon layers using:
It will also handle behind the scenes any case where layers are added or removed from the project, even while your plugin dialog is open, so you don't need to worry about connecting to signals emitted by the project and re-populating your generic combo box.
In a Windows OSGeo4W install, in the bin folder, you will find a batch file called qgis-designer or qgis-ltr-designer.
This batch file will open Qt Designer with all the QGIS custom widgets available. I suggest to open your
.ui file, delete the
QComboBox and replace it with a
QgsMapLayerComboBox as in the screenshot below.
Then you can edit your
plugin.py file and copy the code below. Note that I have created one additional method,
populate_combobox_2(), and connected it to the
layerChanged signal of the
QgsMapLayerComboBox, so that the Name combo box (comboBox_2) is updated whenever the layer selected in the layer combo box changes.
You will also need to add the following line to the imports at the top of the file:
from qgis.core import QgsMapLayerProxyModel
Other section of
.py file which will populate your combo boxes:
"""Run method that performs all the real work"""
# Create the dialog with elements (after translation) and keep reference
# Only create GUI ONCE in callback, so that it will only load when the plugin is started
if self.first_start == True:
self.first_start = False
self.dlg = GetMapDialog()
# Connect signal to slot which will update comboBox_2 whenever selection in comboBox changes
# show the dialog
selectedLayer = self.dlg.comboBox.currentLayer()
self.dlg.comboBox_2.addItems(sorted([i for i in selectedLayer.uniqueValues(selectedLayer.fields().lookupField('names'))]))