How to Change the Active Layer in QGIS Console – Complete Tutorial

pyqgisqgis

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?

Best Answer

For QGIS3 this functionality seems to be mapped to QgsProject now:

# I get the layer object by the name 'na_roads_Prov'
roads = QgsProject.instance().mapLayersByName('na_roads_Prov')[0]
# I select the layer object
iface.setActiveLayer(roads)