6

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'

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Sep 22, 2015 at 13:00

1 Answer 1

6

Your approach is correct and working. However, the result you get back from layer.getFeatures is a QgsFeatureIterator and not a QgsFeature. You have potentially more than 1 feature in selection. You can simply iterate over your selection to get all the features:

for feature in selection:
 geom = feature.geometry()
 # do something with geom
answered Sep 22, 2015 at 13:23
3
  • Just a last question: if I'm sure that the result from the layer.getFeatures is only one feature, then is it correct to use the sintax: selection.next(), intead of the iteration? Commented Sep 22, 2015 at 14:41
  • More generally, it is a Python iterator look at Python list iterator behavior and next(iterator) Commented Sep 22, 2015 at 15:01
  • Dear @chkaiser, dear all, thanks for your answer. The feature geometry selection works, but unfortunately I have another problem. In some cases there is not the feature with requested "CODICE", and this is because I have to match two different layers to understand when they have the same code. When the two layers don't have the same code the getFeature gives me an error and the program stops. In this case I would like to skip to request to start another one. Do you have some suggestions? Really thanks. Commented Jan 24, 2016 at 18:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.