4

I have a QGIS project and in that project there is a print composer layout titled mainmap. This print composer layout has my desired layout items like a title, scalebar, and legend. mainmap also has a map with the default name Map 1.

I can use the Python code below in the Python Console to move the extent of the project canvas to the extent of the QgsRectangle just fine.

rect = QgsRectangle(1196381.0,655556.0,1204217.0,660632.0)
canvas = qgis.utils.iface.mapCanvas()
canvas.setExtent(rect)
canvas.refresh()

I would now like to use Python to also change the extent of mainmap/Map 1 in the print composer to the same QgsRectangle referenced in the code above. I can see the Extent settings in the Item Properties (see the image below) and I can set them manually. What Python code would I do to set the extents of Map 1 to match the map canvas?

enter image description here

1 Answer 1

5

See the code example below, which will change the extent of the map item with the id map1 in the layout named test to the same extent as the map canvas extent:

canvas = iface.mapCanvas()
manager = QgsProject.instance().layoutManager()
layout = manager.layoutByName("test")
mapItem = layout.itemById('map1')
#make sure that it is a MapItem
if type(mapItem).__name__ == "QgsLayoutItemMap":
    mapItem.setExtent(canvas.extent()) 

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.