Programmatically Get Selected Layers from QGIS Legend

layerspyqgisqgis

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?

Best Answer

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

iface.layerTreeView().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()

the selectedLayers() 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 by selectedLayers(). 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(layer.name())
    elif layer.type() == QgsMapLayer.RasterLayer:
        print(layer.name())
    elif layer.type() == QgsMapLayer.PluginLayer:
        print(layer.name())
    else:
        raise Exception('Should never happen')