Sunday 31 May 2015

pyqgis - Getting selected feature geometry using QGIS API?


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?



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...