4

I have a vector layer that I need to filter and zoom to extent of the layer whilst the filter is applied. Most of the examples I see only zoom to selected features. I have managed to filter using

p_id = 31
filter_rule = ' id = %s ' % p_id
qExp = QgsExpression(filter_rule)
qReq = QgsFeatureRequest(qExp)
features = layer.getFeatures(qReq)

How can I zoom to the extent to only show the feature which corresponds to the filter?

1 Answer 1

4

One method is to filter the features using the setSubsetString() method. Once your layer is filtered, you can then set the canvas extent which is only affected by the remaining features of the layer:

layer = iface.activeLayer()
canvas = qgis.utils.iface.mapCanvas()

p_id = 31
filter_rule = ' id = %s ' % p_id    
layer.setSubsetString(filter_rule)  
canvas.setExtent(layer.extent())

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.