I'm using a qgis plugin with very basic gui with 4 QgsMapLayerComboBoxes, I'll use each one to select a layer. I want to retrieve the currently selected item's name for each combobox (a vector layer) as a variable in my function so I can edit each layer.

As of right now, I added this code to my def run(self) :


In my function I have this layer1 = mapLayerComboBox1.layer() (same with other layers), I'm not sure yet how to retrieve the layer's name (to use with mapLayersByName similarly to how it would be feasible using QComboBox.currentText() something I learned reading PyQGIS using selected layer from a combobox) but even before that I receive the following error when I test the plugin:

layer1 = mapLayerComboBox1.layer()
NameError: name 'mapLayerComboBox1' is not defined

At the start of my MainPlugin.py I added this from qgis.gui import QgsMapLayerComboBox following answers from this thread Debugging Global name ''QgsMapLayerComboBox' is not defined? but I still get the error. Following the second answer (which advises to use from YourPluginName_dialog_base import QgsMapLayerComboBox) I receive a critical error:

File "C:/OSGEO4~1/apps/qgis-ltr/./python\qgis\utils.py", line 793, in _import
mod = _builtin_import(name, globals, locals, fromlist, level)
ModuleNotFoundError: No module named 'mypluginname_dialog_base'

1 Answer 1


To get the selected layer use:

selectedlayer = self.dlg.mapLayerComboBox1.currentLayer()

Or combined with a filter its:

selectedlayer = self.dlg.mapLayerComboBox1.currentLayer()

In case you really want the name, not the layer, you can use

selectedlayername = selectedlayer.name()

About your Error NameError: name 'mapLayerComboBox1' is not defined, you need to reference to your Plugins dialog. If youve done it with PluginBuilder-Plugin, that should be

layer1 = self.dlg.mapLayerComboBox1.layer()

Note that .layer() Returns the layer currently shown at the specified index within the combo box as stated in the docs. So you need to add an integer for the index, such as .layer(2). To get the currently selected layer use .currentLayer() instead.

  • Thank you it does work perfectly. Commented Sep 28, 2021 at 13:24

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.