2

For each new QGIS project, I want to add a few layouts from prepared templates.

All templates are vertically oriented (A4 portrait). Inspecting the templates (the XML contents), I can see a <LayoutItem> with a proper size="210,297,mm", as in this example:

<LayoutItem positionLock="false" zValue="0" frame="false" referencePoint="0" itemRotation="0" id="" size="210,297,mm" outlineWidthM="0.3,mm" positionOnPage="0,0,mm" position="0,0,mm" visibility="1" type="65638" frameJoinStyle="miter" opacity="1" background="true" blendMode="0" uuid="{3156912c-ce6e-4d02-8dfc-bc7c36b8f738}" templateUuid="{3156912c-ce6e-4d02-8dfc-bc7c36b8f738}" groupUuid="" excludeFromExports="0">

Adding templates manually

If I add the templates using the GUI, it works. The template is added and I get a new layout, with the correct page orientation, as expected.

Add template using GUI

Adding templates with PyQGIS

Since I want to add a few templates, I would like to add them using PyQGIS.

The minimal code is this:

project = QgsProject.instance()
layout = QgsPrintLayout(project)
layout.initializeDefaults()

with open('/home/jgr/Templates/reserva.qpt') as f:
    template_content = f.read()
    doc = QDomDocument()
    doc.setContent(template_content)
    items, ok = layout.loadFromTemplate(doc, QgsReadWriteContext(), False)
    layout.setName('reserva')
    project.layoutManager().addLayout(layout)

The layout is created without the proper orientation. The generated layout from the templates is horizontally oriented, but the template is vertically oriented.

Add template using PyQGIS

What am I missing in this PyQGIS script?

1 Answer 1

4

layout.initializeDefaults() creates an almost empty layout. The generated layout has already one page, with the default orientation.

Setting clearExisting = True when calling layout.loadFromTemplate rewrites the default layout with the template's orientation. More info on the loadFromTemplate documentation.

The entire code should be:

project = QgsProject.instance()
layout = QgsPrintLayout(project)
layout.initializeDefaults()

with open('/home/jgr/Templates/reserva.qpt') as f:
    template_content = f.read()
    doc = QDomDocument()
    doc.setContent(template_content)
    items, ok = layout.loadFromTemplate(doc, QgsReadWriteContext(), True)
    layout.setName('reserva')
    project.layoutManager().addLayout(layout)

Your Answer

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

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