QGIS API Geometry – How to Get Selected Feature Geometry Using QGIS API

geometrypyqgis

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?

Best Answer

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.