Wednesday, 7 September 2016

qgis 3 - How to get selected layers in QGIS3 from python


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?



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


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...