Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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? Thank you!

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.