Developing a QGIS plugin, I found that if no layer is selected in the Layers panel I can iterate over all layers and do anything to them, but "activate" them.

Could someone give me a hint please?

1 Answer 1


You can set the active layer using the qgis.utils.iface object (i.e. QgisInterface):

qgis.utils.iface.setActiveLayer(QgsMapLayer)  # returns bool
# or
qgis.utils.iface.legendInterface().setCurrentLayer(QgsMapLayer)  # returns bool

Clearing the selection, or the active layer (underlined QTreeWidget item in QGIS 2.0), in the legend is a bit more involved:

from PyQt4.QtCore import *
from PyQt4.QtGui import *
lg = qgis.utils.iface.mainWindow().findChild(QTreeWidget, 'theMapLegend')
lg.selectionModel().clear()  # clear just selection
lg.setCurrentItem(None)  # clear selection and active layer

There are three ways to retrieve the current layers, relative to what you may want to do:

~ via QList< QgsMapLayer * > QgsLegendInterface::layers()

qgis.utils.iface.legendInterface().layers()  # returns [layer, ...]

~ via QList< QgsMapLayer * > QgsMapCanvas::layers():

qgis.utils.iface.mapCanvas().layers()  # returns [layer, ...]

~ via const QMap< QString, QgsMapLayer * > & QgsMapLayerRegistry::mapLayers():

QgsMapLayerRegistry.instance().mapLayers()  # returns {'layer_id': layer, ...}

Reference these answers for information about the differences in those layer collections.

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.