I work on a QGIS Plugin in python. This plugin import in QGIS project several print layout (A4/A3/Landscape/Portait format) from a directoty of my laptop to the layout manager. The plugin add also a vector layer in my QGIS project. I would like that when I open a layout from the layout manager, the map of this layout is centered on the extent of the layer in my project. I have tried the code below but it does not zoom in correctly on the layer.

project = QgsProject.instance()

zip_layer = QgsVectorLayer("C:/Users/Thysma/Documents/Stage/Data/zip.shp", "Aire d'étude",'ogr')                   

composition = QgsPrintLayout(project)
document = QDomDocument()
template_file = open('C:/Users/Thysma/Documents/Stage/Composeurs/A3 Paysage.qpt')
template_content = template_file.read()
composition.loadFromTemplate(document, QgsReadWriteContext()) 

layout = project.layoutManager().layoutByName('A3 Paysage')        
map = layout.itemById("map")      
map.attemptMove(QgsLayoutPoint(0.150, 21.610, QgsUnitTypes.LayoutMillimeters))
map.attemptResize(QgsLayoutSize(342.235, 275.240,QgsUnitTypes.LayoutMillimeters))

The zoom made gives me the following rendering (the map is not zoomed in on the total extent of the layer): enter image description here

1 Answer 1


Instead of setExtent() you should use zoomToExtent() method.


layer_extent = zip_layer.extent()

If you wish too zoom out very slightly from the layer extent you can use the grow() method on the QgsRectangle layer_extent object.


layer_extent = zip_layer.extent()
layer_extent.grow(0.1)#pass a sensible value depending on crs used and map scale

The value you pass to the grow() method will depend on size/scale of your layer and whether you are working with meter or geographic degree units etc.

  • 1
    Thank you ! This code perfectly answers my question :) Apr 13, 2021 at 14:36

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.