I'm trying to write a python script that zooms to each layer's extents and then exports the canvas as an image after every zoom.
I wrote a for loop that iterates through each layer, makes each one active, one at a time, then fetches the extents of layer while it is active, and then zooms to the extent.
While the script successfully iterates through each layer, the map canvas does not change meaning that it only zooms to the first layer extent in the list and stops there.
I even added a
canvas.refresh() at the end of the loop, but nothing. Additionally, I added a sleep function using
time.sleep(5), but no luck either.
I can see that each layer in the list being iterated through because each is selected and highlighted via
setActiveLayer, but how can I zoom each active layer's extents one at a time, perhaps every 5 seconds? And how can I script the map canvas to reflect this selection, and zoom?
This is the code:
import math import time from qgis.core import QgsProject for layer in QgsProject.instance().mapLayers().values(): qgis.utils.iface.setActiveLayer(layer) extent = layer.extent() canvas.setExtent(extent) iface.mapCanvas().zoomScale(700) time.sleep(5) canvas.refresh() print(extent)