4

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?

2 Answers 2

5

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)
1
  • thank you for this. any idea how to modify 'A0' to be a custom page size in mm? documentation seems to be lacking for setPageSize...
    – user20408
    Jun 14 at 19:50
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.

1

Your Answer

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

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