[GIS] Getting a layer that is not active with PyQGIS

pyqgisqgisqgis-2

I want to retrieve attributes of selected objects on a layer with PyQGIS.
All example I see is for the active layer:

vlayer=qgis.utils.iface.activeLayer()
selected_bf = vlayer.selectedFeatures()

But, my features are not on the active layer. What is the way to say that vlayer is another layer but not the active layer?


I put this:

import processing
from qgis.core import * 
vlayer = processing.getObject('mylayer')
selected_objects = vlayer.selectedFeatures()

as a filter expression in QGIS 2.8 but I can't open QGIS after.

Error: "AttributeError: 'NoneType' object has no attribute 'selectedFeatures'"

Best Answer

You can also reference a layer by it's name:

layer = QgsMapLayerRegistry.instance().mapLayersByName("MY_LAYER_NAME")[0]
selected = layer.selectedFeatures()

if your not sure of the name, you can look for it:

layer=None
for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
    if lyr.name() == "MY_LAYER_NAME":
        layer = lyr
        break

Note for QGIS 3.x: in QGIS3 you should replace QgsMapLayerRegistry by QgsProject (see this answer).

Related Question