1

I am interested in making reproducible PDF figures in QGIS3, and therefore want to work from the console/PyQGIS.

Using some previous helpful advice from PDF Output with Python the problem is successfully reduced to setting up the QgsPrintLayout. I am not sure how to do this, below is my best attempt so far:

#setup the background classes for managing the project
canvas =iface.mapCanvas()
manager = project.layoutManager()
#new layout
layout = QgsPrintLayout(project)
layout.initializeDefaults()
layout.setName('console')
itemMap = QgsLayoutItemMap(layout)
itemMap.setExtent(canvas.extent())
layout.addLayoutItem(itemMap)
#add the layout to the manager
manager.addLayout(layout)

The "console" layout is successfully added to QGIS 3 and I can open it to see if the content is satisfactory. The map does not render and its extent is nan,nan,nan,nan.

How do I setup the extent and size of the map object in the layout?


SOLVED. The following code produces a map without issues.

#get a reference to the layout manager
manager = project.layoutManager()
#make a new print layout object
layout = QgsPrintLayout(project)
#needs to call this according to API documentaiton
layout.initializeDefaults()
#cosmetic
layout.setName('console')
#add layout to manager
manager.addLayout(layout)
#create a map item to add
itemMap = QgsLayoutItemMap.create(layout)
#using ndawson's answer below, do this before setting extent
itemMap.attemptResize(QgsLayoutSize(6,4, QgsUnitTypes.LayoutInches))
#set an extent
itemMap.setExtent(canvas.extent())
#add the map to the layout
layout.addLayoutItem(itemMap)
  • Thanks for including the "solved" code. I'd like to ask about one thing. Where in the documentation did you find that you need to initializeDefaults()? I can't find this anywhere. – Erich Purpur Jan 17 at 14:51
  • I was not able to find the API documentation on why initializeDefaults() is required, but try this example without it: gis.stackexchange.com/a/309551/75563 I found that not only is the PDF way off, but QGIS crashed as well when pressing Export to PDF ... – RobLabs Jan 22 at 20:51
4

You need to set a size for the map item (usually you do this before setting the extent):

itemMap.attemptResize(QgsLayoutSize(50, 60, QgsUnitTypes.LayoutMillimeters)) itemMap.attemptMove(QgsLayoutPoint(1,2,QgsUnitTypes.LayoutMillimeters)) itemMap.setExtent(...)

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.