3

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

I tried

selectedLayers = iface.legendInterface().selectedLayers()

as suggested in How to get programmatically 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?

4

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, privacy policy and cookie policy

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