[QGIS-Developer] QgsPrintLayout Setup from PyQGIS 3

Nyall Dawson nyall.dawson at gmail.com
Wed Mar 28 15:04:59 PDT 2018


On 29 March 2018 at 08:03, Nyall Dawson <nyall.dawson at gmail.com> wrote:
> On 27 March 2018 at 23:55, Brian Libgober <libgober at gmail.com> wrote:
>> I am interested in making reproducible PDF figures in QGIS3, and therefore
>> want to work from the console/PyQGIS. Thanks to some previous helpful advice
>> here, 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?
>>
>
> I answered over on stackexchange too, but for completeness:
>
> 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(...)
>
> This is because the call to setExtent uses the item size for various
> scale and aspect ratio calculations, and initially a new item is
> created with an empty size.

Also, you may want to consider using zoomToExtent(...) instead -
setExtent can change the item's size to ensure that the map item
matches the aspect ratio of the extent, whereas zoomToExtent will
never resize the item and instead zooms out the extent until it fits
completely within the existing item size.

Nyall


More information about the QGIS-Developer mailing list