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')
QgsProject.instance().addMapLayer(zip_layer)
composition = QgsPrintLayout(project)
document = QDomDocument()
template_file = open('C:/Users/Thysma/Documents/Stage/Composeurs/A3 Paysage.qpt')
template_content = template_file.read()
template_file.close()
document.setContent(template_content)
composition.loadFromTemplate(document, QgsReadWriteContext())
project.layoutManager().addLayout(composition)
layout = project.layoutManager().layoutByName('A3 Paysage')
map = layout.itemById("map")
map.setExtent(zip_layer.extent())
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):