0

I would like to list all the selected layers in the QGIS Layers Panel with PyQGIS. I'm looking for a PyQGIS function returning a list of all selected layers or a method to check if a layer is selected.

I tried iface.activeLayer() but it's only returning the last layer selected.

# not working (only last selected layer returned):
layers = iface.activeLayer()
print(layers)
>>> <QgsMapLayer: 'TOPO' (ogr)>

I also tried to loop on all layers but couldn't find a method to check if a layer is selected or not:

# not working either:
layers = QgsProject.instance().mapLayers()
for layer_name, layer in layers.items():
    if layer.isSelected():
        print(layer)
>>> AttributeError: 'QgsRasterLayer' object has no attribute 'isSelected'
0

1 Answer 1

4

You have selected layers (mouse-click on layer in tree / CTRL + mouse-click for multiple) and checked layers (checkbox clicked --> layers visible on the map canvas).

For selected layers you can do (answer from here):

iface.layerTreeView().selectedLayers()

For checked layers you can do (answer from here):

iface.mapCanvas().layers()

Your Answer

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

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