Graphics Reference
In-Depth Information
provider = layer.dataProvider()
for feature in provider.getFeatures(QgsFeatureRequest()):
...
If you want to search for features based on some criteria, you can use the Qg-
sFeatureRequest object's setFilterExpression() method, as follows:
provider = layer.dataProvider()
request = QgsFeatureRequest()
request.setFilterExpression('"GENDER" = "M"')
for feature in provider.getFeatures(QgsFeatureRequest()):
...
Once you have the features, it's easy to get access to the feature's geometry, ID, and attrib-
utes. For example:
geometry = feature.geometry()
id = feature.id()
name = feature.attribute("NAME")
The object returned by the feature.geometry() call, which will be an instance of
qgis.core.QgsGeometry , represents the feature's geometry. This object has a large
number of methods you can use to extract the underlying data and perform various geo-
spatial calculations.
Spatial indexes
In the previous section, we searched for features based on their attribute values. There are
times, though, when you might want to find features based on their position in space. For
example, you might want to find all features that lie within a certain distance of a given
point. To do this, you can use a spatial index , which indexes features according to their
location and extent. Spatial indexes are represented in QGIS by the QgsSpatialIndex
class.
For performance reasons, a spatial index is not created automatically for each vector layer.
However, it's easy to create one when you need it:
provider = layer.dataProvider()
index = QgsSpatialIndex()
Search WWH ::




Custom Search