Tuesday 30 October 2018

python - Iterating over selected features in QGIS Processing


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?



Answer



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()]

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...