[GIS] Changing active layer in combo box in PyQgis plugin

pyqgisqgis-plugins

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.

Best Answer

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()
>>>cb.show()

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()
grid

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 ]

comboBox.addItems(layers_names)

comboBox.show()

and produces this:

enter image description here

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

>>>selectedLayerIndex = comboBox.currentIndex()
>>>selectedLayer = layers[selectedLayerIndex].name()
>>>selectedLayer
u'grid'
Related Question