I came across with a problem. I don't know how to change active layer by using a combo box object (QComboBox). I manage to create a list of names but I don't know how to change active layer in QGIS plugin Combo Box yet.

index = QgsMapLayerRegistry.instance().mapLayers().values()

for i in index:
    if i.type() == QgsMapLayer.VectorLayer:
        self.dockwidget.active.addItem( i.name(), i )

Above code creates a list of my layers, but I can not change active layer with this method. Whenever active layer is changed, combo box should also update its reference.

Can you help me? I am using Qgis 2.16.

1 Answer 1


In this case it's preferable to use directly a QgsMapLayerComboBox object. I's very easy. For example, in next situation with 4 layers:

enter image description here

at the Python Console of QGIS I can do:

>>>from qgis.gui import QgsMapLayerComboBox
>>>cb = QgsMapLayerComboBox()

Selecting 'grid' layer (see next image):

enter image description here

next command prints correctly the name of selected layer because selection was automatic:

>>>print cb.currentLayer().name()

as it can also be observed at next image:

enter image description here

At the plugin you need:

    def __init__(self, iface):
        self.cb = QgsMapLayerComboBox(self.dlg)
        okBtn = self.dlg.okButton
        okBtn.connect(okBtn, SIGNAL("clicked()"), self.your_function)

    def your_function(self):            
        layer = self.cb.currentLayer()   
        #rest of your code

Editing Note:

With your code is:

from qgis.PyQt.QtGui import QComboBox

comboBox = QComboBox()

layers = QgsMapLayerRegistry.instance().mapLayers().values()

layers_names = [ layer.name() for layer in layers ]



and produces this:

enter image description here

Afterwards (equivalent to click in OK button), selecting 'grid' layer:

>>>selectedLayerIndex = comboBox.currentIndex()
>>>selectedLayer = layers[selectedLayerIndex].name()
  • It works but what i looking for is when person click inside qgis legend my shp will update automatically.
    – Losbaltica
    Mar 2, 2017 at 11:26
  • I modified my answer with my equivalent version of your code (see my Editing Note).
    – xunilk
    Mar 2, 2017 at 12:41

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.