1

I used to be able to iterate over selected features using the following script in v2.0.

import processing
features = processing.getfeatures(layer)
for feature in features:
  #Do whatever you need with the feature

However, this doesn't seem to work when I upgraded my QGIS to v2.2. Is there any new way on how to iterate selected vectors?

3

You can use the solutions given in Using processing algorithms from the console:

But if you look at what's in the module (version 2.2):

import processing
dir(processing)

no more getfeatures() or getFeatures()

You can control this with a little function adapted from Script de Python para filtrar por patrón de texto los métodos de Clases en PyQGIS de José Guerrero

import re
def get_patt(keyword, L):
    return [item for item in dir(L) if re.search(keyword,item)]
get_patt("getfeatures",processing)
[]
get_patt("getFeatures",processing)
[]

but there is:

get_patt("features",processing)
['features']

So the command is:

features = processing.features(layer)

But for me, it is easiest with:

without processing:

layer = qgis.utils.iface.activeLayer()

with processing:

layer = processing.getObject("name_of_the_layer")

All the features:

for feat in layer.getFeatures():
     geom= feat.geometry()
     attr =feat.attributes()

Selected features only:

for feat in layer.selectedFeatures():
     geom= feat.geometry()
     attr =feat.attributes()

and, for example, an "universal solution":

if layer.selectedFeatureCount():
     geom = [feat.geometry() for feat in layer.selectedFeatures()]
else:
     geom = [feat.geometry() for feat in layer.getFeatures()]
  • Thanks gene for your detailed reply. Indeed the recent version (v2.2) uses 'processing.features(layer)' instead of the old 'processing.getfeatures(layer)'. Many thanks! – jre May 28 '14 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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