Sunday 28 July 2019

qgis 3 - QgsPrintLayout Setup from PyQGIS 3?


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)

Answer



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(...)


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...