4

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?

4

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')

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.