I want to get the geometry for a selected feature using QGIS API. When extracting geometry for unselected features this is what I typically do:

l = iface.activeLayer()
fs = l.getFeatures() #returns QgsFeatureIterator object
f = fs.next() #returns next QgsFeature object
g = g.geometry() # returns geometry object

I tried doing something similar with only selected features but ran into a problem:

l = iface.activeLayer()
s = l.selectedFeatures() #returns QgsFeature object
g = s.geometry() #throws error. Also dir(s) confirms that s has no geometry() method

How come s has no method geometry()?

Isn't it an instance of the same class as f in the first example?

How can I extract geometry for only the selected feature?


I think s is not a QgsFeature in the strictest sense, because you can have multiple selected features. I'm confused here because I only have one, but once you do the following:

g  = s[0].geometry()

It should index into your selected feature subset, in this case extracting the first (and only) list item, and return the QgsGeometry object.

| improve this answer | |
  • Yes that's because selectedFeatures() returns a list of selected features as QgsFeature. If you have only one selected feature, il returns a list of one QgsFeature. – YoLecomte Sep 15 '18 at 9:28

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.