3

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'"

2 Answers 2

7

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

1
  • But now, I can't open QGIS (I have this as an expression filter). Error: "Name 'QgsMapLayerRegistry' is not defined". Commented Mar 10, 2015 at 17:33
5

Look at Get a list of layer names using PyQGIS`

You can use a simple Python dictionary

names = [layer.name() for layer in QgsMapLayerRegistry.instance().mapLayers().values()]
layers = dict((name,i) for i, name in enumerate(names))
print layers
{u'layer1': 1, u'layer2': 0, u'layer3': 2, u'layer': 3, ...}

or:

canvas= qgis.utils.iface.mapCanvas()
layers = dict((k.name(),i) for i, k in enumerate(canvas.layers()))
print layers
{u'layer1': 1, u'layer2': 0, u'layer3': 2, u'layer': 3, ...}

And to select the layer:

layer1 = canvas.layer(layers['layer1'])
layer2 = canvas.layer(layers['layer2'])
....
# or
layer1 = canvas.layer(1)
layer2 = canvas.layer(2)
....

But if you add a new layer, you must start over, not with the processing module:

import processing
layer1 = processing.getObject('layer1')
layerx =  processing.getObject('newlayer')

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.