Thursday 23 February 2017

pyqgis - How to change the active layer in QGIS Console?


I want my script to perform actions on a particular layer. Online advice I've found so far suggests using the iface method "setActiveLayer()". Makes sense based on the name alone.


Scenario: In the Layers window I have a layer named "Province" highlighted (active). Then I run the following code:



>>> vl = QgsMapLayerRegistry.instance().mapLayer( 'na_roads_Prov' )
>>> iface.setActiveLayer(vl)

Console Output = False


As far as I understand executing this code in the console should move the highlighted "active layer" from "Province" to 'na_roads_Prov'. Yes? Instead the "Province" layer remains highlighted as active, and the console output says "False". Any ideas? Am I not referring to the layer correctly?



Answer



Use mapLayersByName method to get the layer by name


vl = QgsMapLayerRegistry.instance().mapLayersByName('na_roads_Prov')[0]
iface.setActiveLayer(vl)

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...