I created a QPT model with a map inside QGIS. The problem is when I try to select the map under pyQGIS :

qpt = QDomDocument()
layout = QgsLayout(QgsProject().instance())
layout.loadFromTemplate(qpt, QgsReadWriteContext())
mapItem = layout.itemById('Map') # 'Map' is the name of the item map

mapCanvas = iface.mapCanvas()

It returns this error :

AttributeError: 'QgsLayoutItem' object has no attribute 'zoomToExtent'

I know there is a class QgsLayoutItemMap but I don't know how to get it from the QgsLayoutItem map.

And I have another question : in QGIS composer, there is a button when I select my Map called "Set to map canvas extent". What is the equivalent in python ? mapItem.zoomToExtent(mapCanvas.extent()) and then mapItem.refresh() ?


I found the answer to my question : there is one way to get existing QgsLayoutItemMap from opened QPT and it's not the simplest one. You need to ensure you have only one Map per Layout and you can get it with QgsLayout.referenceMap(). The complete explanation is here :


Apparently this is a bug of Windows' QGIS that doesn't happen under Linux. It seams there is no other way to do it in Python API QGIS 3.

EDIT : the second part of my question is always topical.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.