Iterating over features

Now, it's time to discover how to get all the features or a subset of them. The main way to iterate over all features or records of myVector is by using the following code, which shows the ID of each feature:

for feature in myVector.getFeatures():
  feature.id()

This will print a list of all the 653 record IDs as shown here:

0L
1L
...[cut]...
652L

It's not always necessary to parse all records to get a subset of them. In this case, we have to set the QgsFeatureRequest class parameters to instruct getFeatures and then retrieve only a subset of records; in some cases, we must also retrieve a subset of columns.

The following code will get a subset of features and columns:

rect = QgsRectangle( 1223070.695, 2293653.357 , 9046974.211, ...

Get Mastering QGIS - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.