You have to load layers and before set the new extent, tell to your canvas to wait before rendering.
An important thing too is to set your project or canvas CRS. In the code, I left the two but only one work.
Try the code below :
project = QgsProject.instance()
canvas = iface.mapCanvas()
modifications
crs_l93 = QgsCoordinateReferenceSystem("EPSG:2154")
project.setCrs(crs_l93)
canvas.setDestinationCrs(crs_l93)
project.write('C:/CartoIni/Projet/Projet.qgs')
root = QgsProject.instance().layerTreeRoot() # add the root object, as your original code
groupe_aire = root.addGroup("Aires d'étude")
AEE_layer = QgsVectorLayer("C:/Users/Thysma/Documents/Stage/Data/AEE.shp", 'AEE','ogr')
QgsProject.instance().addMapLayer(AEE_layer, False)
groupe_aire.addLayer(AEE_layer)
reg_layer = QgsVectorLayer("C:/Users/Thysma/Documents/Stage/Data/REGION.shp", 'Limites régionales','ogr')
QgsProject.instance().addMapLayer(reg_layer, False)
groupe_aire.addLayer(reg_layer)
canvas.waitWhileRendering() # modification here
extent = AEE_layer.extent()
canvas.setExtent(extent)
canvas.refresh()
| EDIT: if the first code doesn't work |
You can set the extent once the canvas is refreshed a first time :
def set_aee_extent():
extent = AEE_layer.extent()
canvas.setExtent(extent)
# disconnect the signal to avoid calling set_aee_extent again
canvas.mapCanvasRefreshed.disconnect(set_aee_extent)
canvas.refresh()
project = QgsProject.instance()
canvas = iface.mapCanvas()
modifications
crs_l93 = QgsCoordinateReferenceSystem("EPSG:2154")
project.setCrs(crs_l93)
canvas.setDestinationCrs(crs_l93)
project.write("C:/CartoIni/Projet/Projet.qgs")
root = QgsProject.instance().layerTreeRoot() # add the root object, as your original code
groupe_aire = root.addGroup("Aires d'étude")
AEE_layer = QgsVectorLayer("C:/Users/Thysma/Documents/Stage/Data/AEE.shp", 'AEE','ogr')
reg_layer = QgsVectorLayer("C:/Users/Thysma/Documents/Stage/Data/REGION.shp", 'Limites régionales','ogr')
canvas.mapCanvasRefreshed.connect(set_aee_extent)
canvas.setLayers([AEE_layer, reg_layer])
groupe_aire.addLayer(AEE_layer)
groupe_aire.addLayer(reg_layer)
canvas = iface.mapCanvas(), and welcome to GIS SE ! – J. Monticolo Mar 29 '21 at 13:01AEE_layer.extent()? – J. Monticolo Mar 30 '21 at 08:21AEE_layer.extent():<QgsRectangle: 610783.06441810820251703 6745293.08760993927717209, 623023.31778933946043253 6757083.76099352352321148>– Mathys WOHL Apr 01 '21 at 08:48iface.mapCanvas().setExtent(QgsRectangle(610783.06441810820251703, 6745293.08760993927717209, 623023.31778933946043253, 6757083.76099352352321148))and it zooms perfectly to the Orléans - Olivet area. Check your canvas coordinate system. – J. Monticolo Apr 01 '21 at 09:20canvas = iface.mapCanvas()(even if it didn't produce the good result now, because here, you create your own canvas and you don't display it). – J. Monticolo Apr 01 '21 at 14:19