Programmatically get selected layers from the QGIS legend?

Programmatically get selected layers from the QGIS legend?

My QGIS plugin exports all layers from QGIS to KML format. Now I'd like to export only selected layers. However, I can't find any hints in QGIS API. Is it possible to iterate over selected layers in the QGIS legend?

The original question was referred to QGIS 2.x version.

QGIS 3.x

To get the layers selected in the TOC in QGIS 3.x check this answer.

with the iface object, it is possible to get the layerTreeView, which has a method selectedLayers():


more methods on QgsLayerTreeView in the docs:

QGIS 2.x

You can get the layers selected in the TOC with something like this

selectedLayers = iface.legendInterface().selectedLayers()

theselectedLayers()method in QgsLegendInterface does the trick. But take into account that:

  • If a group is selected neither the group itself, neither the layers within are returned byselectedLayers(). You must select it in the GUI one by one.
  • Probably you want to filter the layers by their type (TileLayer, QgsRasterLayer, QgsVectorLayer,… )

A more complete example:

selectedLayers = iface.legendInterface().selectedLayers() for layer in selectedLayers: if layer.type() == QgsMapLayer.VectorLayer: print( elif layer.type() == QgsMapLayer.RasterLayer: print( elif layer.type() == QgsMapLayer.PluginLayer: print( else: raise Exception('Should never happen')