I have a vector layer (grid). Currently I select some tiles with the select tool and paste some Python code to get information about these features.

layer = qgis.utils.iface.activeLayer()
selected_features = layer.selectedFeatures()
for i in selected_features:

Now, I want to get the feature values from the tiles which I can see on the map canvas, without selecting them.

There were two possibilities.

  1. Selecting only the features which are fully visible ("contained" in the map canvas)
  2. Selecting all features which are also partly visible ("intersecting" the map canvas)

Is there a way to do this with PyQGIS?

1 Answer 1


Yes, it is possible by using a QgsFeatureRequest with 'setFilterRect' method. The argument of this method is a QgsRectangle object obtained for visible part of Map Canvas with its 'extent' method (QgsMapCanvas class). I tried out my approach with this code:

layer = iface.activeLayer()
mapcanvas = iface.mapCanvas()
rect = mapcanvas.extent()

request = QgsFeatureRequest().setFilterRect(rect)

selected_feats = layer.getFeatures(request)

attr = [ feat.attributes() for feat in selected_feats ]

print attr

print len(attr)

and world_borders shapefile that has 3784 features. After running the code with the next image situation:

enter image description here

I got the display of only 77 visible features attributes (printed result at the Python Console of GIS).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.