6

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?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jun 15, 2016 at 21:03

1 Answer 1

5

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).

answered Jun 16, 2016 at 9:05
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.