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

asked Feb 15, 2020 at 0:03

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()) 
Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
answered Feb 15, 2020 at 5:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.