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?

2 Answers 2


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
  • Cool, thanks! On a side note, do you know how to script the same thing in ArcMap?
    – Waterman
    Jun 15, 2018 at 0:17
  • @Waterman no, I do not Mar 23, 2020 at 21:47

Use mapLayersByName method to get the layer by name

vl = QgsMapLayerRegistry.instance().mapLayersByName('na_roads_Prov')[0]
  • Much appreciated! I see the original method I was trying to use, "mapLayer", requires the layer ID. Out of curiosity I've tried locating the layer ID by looking at the layer properties, and also by typing into the following into the console... layer = qgis.utils.iface.activeLayer() layer.getLayerID() BUT... the result is as follows... Traceback (most recent call last): File "<input>", line 1, in <module> AttributeError: 'QgsVectorLayer' object has no attribute 'getLayerID' Any easy way to find a layer's ID? Thank you.
    – Waterman
    Oct 26, 2015 at 15:29
  • layer.id() will get you the id. Oct 26, 2015 at 15:41
  • Also, presumably you can use "mapLayersByName" to set multiple layers to the instance pointer at the same time? Can you show me the correct syntax for two layers? If you'd like I can pose this as a stand alone question. Thank you.
    – Waterman
    Oct 26, 2015 at 15:41
  • Layer names are not unique in QGIS so you can have many layers return from that same function call. e.g you could have 3 x na_roads_Prov in your project. Why. No idea but you can.
    – Nathan W
    Oct 27, 2015 at 13:17
  • A basic question as I´m not a programmer: how to use that code layer.id()? I suppose if paste in Python console it gives me the id of the layer, right? But gives me error... May 12, 2016 at 8:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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