PyQGIS – Fix AttributeError When Getting Selected Layers in QGIS

attributeerrorlayerspyqgisselect

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?

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