1

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?

4

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.

  • 1
    That cleared things up for me, thank you. I am still not used to reading this kind of documentation, so thank you for explaining how one would approach such a question! So, basically: when setting a filter expression => QgsFeatureRequest() must be used, when just iterating => QgsFeatureRequest() is optional. So, I guess the reason that you see it so often in iteration examples, is mainly so that one gets used to it, and does not forget it later on, when it becomes necessary. Or that the code looks more complete. – BritishSteel Jan 28 '15 at 8:12
  • Right, it might be for developers to be aware of the optional function argument. After the first time, you probably won't use it if not necessary. – Germán Carrillo Jan 28 '15 at 13:44

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.