QGIS: Filtering Features

  • Software: QGIS 3.28
  • OS: Any
  • Updated: May 2023

You need to use pyqgis to filter through features on your screen. This will assume you have your active layer active in the layer of contents.

In this example you use pyqgis to select by attribute.

lyr = iface.activeLayer()
exp = QgsExpression('name ILIKE \'%qgis%\'')
request = QgsFeatureRequest(exp)
for feature in lyr.getFeatures(request):
    print(feature['name'])

In this example you have features selected (possibly by mouse) and use pyqgis to run through that selection.

lyr = iface.activeLayer()
for feature in lyr.selectedFeatures():
    print(feature['field'])

In this example you are using pyqgis to filter the data by map extent

lyr = iface.activeLayer()
extent = iface.mapCanvas().extent()
request = QgsFeatureRequest()
request.setFilterRect(extent)
for feature in lyr.getFeatures(request):
     print(feature['label'])