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'

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
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?
    – Chlorine
    Commented Sep 22, 2015 at 14:41
  • More generally, it is a Python iterator look at Python list iterator behavior and next(iterator)
    – gene
    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.
    – Chlorine
    Commented Jan 24, 2016 at 18:00

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.