6

Anyone know how to zoom to the extent of a Vectorlayer in QGIS using python plugin?

2 Answers 2

11

You'd get the app's Map Canvas and set its extent.

canvas = qgis.utils.iface.mapCanvas()
canvas.setExtent(layer.extent())

You might want to read this tutorial.

2
  • 1
    to use a custom extent use: canvas.setExtent(QgsRectangle(xmin,ymin,xmax,ymax))
    – RutgerH
    Mar 16, 2016 at 22:07
  • Additionally, you may use canvas.refresh() Dec 31, 2018 at 8:52
1

This won't work if the CRS of the vector layer is different from the CRS of the project. This could be a better solution: project the extent of the vector layer to the CRS of the project before zooming, like so:

canvas = iface.mapCanvas()
xform = QgsCoordinateTransform(the_layer.crs(),
                               canvas.mapRenderer().destinationCrs())
canvas.setExtent(xform.transform(the_layer.extent()))
canvas.refresh()
1

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.