5

How can I get the selected layers in QGIS 3 with PyQGIS?

I tried:

selectedLayers = iface.legendInterface().selectedLayers()

as suggested in Programmatically get selected layers from the QGIS legend?, but it seems that there is an API breaking change

QgsLegendInterface was removed. It was replaced by layer tree API (QgsLayerTreeNode class and others). Methods that deal with custom actions in main window's layer tree context menu were moved to QgisInterface:

I then tried:

selectedLayers = QgsProject.instance().layerTreeRoot().selectedLayers()

but I get an error about:

AttributeError: 'QgsLayerTree' object has no attribute 'selectedLayers'

What's the correct way to get the selected layers in QGIS3?

1 Answer 1

10

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: https://qgis.org/api/classQgsLayerTreeView.html

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.