Sunday 22 May 2016

qgis - Why use QgsFeatureRequest() when iterating?


I am unclear on why one should use QgsFeatureRequest() when iterating over a file’s features.


Let’s say I would like to print out all IDs in my currently active dataset. Now, most examples will provide something like this:


lyr = iface.activeLayer()
prov = lyr.dataProvider()
for feature in prov.getFeatures(QgsFeatureRequest()):
print feature.id()



Whereas the following, without referring to QgsFeatureRequest(), would yield the same result:


lyr = iface.activeLayer()
prov = lyr.dataProvider()
for feature in prov.getFeatures():
print feature.id()


I’d assume that the right way is using QgsFeatureRequest(), as most quality sources include it, but can someone explain what it actually does, and why one should use it?




Answer



As you can see in the QGIS API docs, when you call getFeatures() with no arguments, QGIS gets a QgsFeatureRequest() by default.


That is, QgsFeatureRequest() is the default value for the first argument of getFeatures(). You can choose whether or not passing it, the result is the same.


Also from the docs, by calling QgsFeatureRequest() you:



construct a default request: for all features get attributes and geometries.



However, if you want to pass a filter expression to getFeatures(), you must pass a QgsFeatureRequest(expression) as done in How to select and zoom in features from a QGIS Python Plugin.


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...