5

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 python?

2

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

  • Thank you. This works for layers which have the same projection as the project coordinate reference system. How I have to change the code for layers which are "on the fly" projected? – Stefan Jun 16 '16 at 10:00
  • You can use QgsCoordinateTransform for this. By using QgsCoordinateTransform.transform(QgsPoint) you can get the corners of your canvas extent and create the rectangle for your layer. – okorkut Jun 16 '16 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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