3

I am trying to create an A0 layout from PyQGIS. I tried the following code but it doesn't work.

from qgis.core import *

manager = QgsProject.instance().layoutManager() 
layouts_list = manager.printLayouts()
for l in layouts_list:
    l.clear()

layout = QgsPrintLayout(QgsProject.instance())  
layout.setName("TEST")
layout.initializeDefaults()
page = QgsLayoutItemPage(layout)
pageSizes = QgsPageSizeRegistry()
pageSize = pageSizes.find("A0")[0]
orientation = QgsLayoutItemPage.Landscape
valid = page.setPageSize(pageSize.displayName, orientation)
print(valid, page.pageSize().width(), page.pageSize().height(), page.orientation())

manager.addLayout(layout)

When I execute this code the layout is created and I get the following message in the console:

True 1189.0 841.0 1. True means that the setPageSize was a success and the sizes are correct.

But when I open the layout in the interface I always get an A4 page.

Am I doing something wrong?

1

Try using the following which uses the pageCollection() method to manage the page settings:

layout = QgsPrintLayout(QgsProject.instance())  
layout.setName("TEST")
layout.initializeDefaults()
pc = layout.pageCollection()
pc.pages()[0].setPageSize('A0', QgsLayoutItemPage.Orientation.Landscape)
manager.addLayout(layout)
0

typo : The orientation belongs directly to QgsLayoutItemPage

from qgis.core import *
manager = QgsProject.instance().layoutManager() 
layout = QgsPrintLayout(QgsProject.instance())  
layout.setName("TEST")
layout.initializeDefaults()
pc = layout.pageCollection()
pc.pages()[0].setPageSize('A0', QgsLayoutItemPage.Landscape)
manager.addLayout(layout)

This code works.

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.