How can I get a feature's geometry from selection by attribute?
For instance from a point layer I want to get the geometry by the field CODICE filter (CODICE = A001).
I tried with:
layer = QgsMapLayerRegistry.instance().mapLayersByName("My_layer")[0]
selection = layer.getFeatures(QgsFeatureRequest(QgsExpression("\"CODICE\" = 'A001'")))
geom = selection.geometry()
It doesn't work, and the python console error is:
AttributeError: 'QgsFeatureIterator' object has no attribute 'geometry'
Best Answer
Your approach is correct and working. However, the result you get back from
layer.getFeatures
is aQgsFeatureIterator
and not aQgsFeature
. You have potentially more than 1 feature inselection
. You can simply iterate over your selection to get all the features: