8

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?

1 Answer 1

10

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')
1
  • It doesn't work for QGIS 3.x
    – Ken T
    Aug 3, 2019 at 7:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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