PyQGIS Features – Zooming to Feature Without Selecting It Using PyQGIS

featurespyqgiszoom

When I need to zoom to a feature, I have to select it first using layer.select(feature.id()) then I can zoom using mapCanvas.zoomToSelected(layer).

layer = iface.activeLayer()
layer.select(1)
iface.mapCanvas().zoomToSelected(layer)

QgsMapCanvas has only zoomToSelected() method related to a layer. My problem is that I should not change the currently selected features when I want to zoom to another feature.

Is there a way to zoom to a feature without selecting it?

Best Answer

You can use setExtent to the bounding box of the feature:

layer = iface.activeLayer()

feats = {f.id():f.geometry().boundingBox() for f in layer.getFeatures()}
canvas = iface.mapCanvas()
canvas.setExtent(feats[1])
canvas.refresh()