PyQGIS Layout – Adding Page After Populating

print-composerpyqgisqgis

TL;DR How can I add items to the page (QgsLayoutItemPage) without using layout?

I want to add an item to the 2nd (or 3rd, …) page in the project layout. Normally, I can add the item to the 2nd page by specifying the layout coordinates using the following script in this way:

  1. Initialize a layout,
  2. Add new page (2nd page) and
  3. Add items to the layout (using the layout coordinates)
import os
from qgis.PyQt.QtGui import QFont

layout_name = "LAYOUT_NAME"
project = QgsProject.instance()

layout_manager = project.layoutManager()
layouts = layout_manager.printLayouts()

# remove the same named layout 
for layout in layouts:
    if layout.name() == layout_name:
        layout_manager.removeLayout(layout)

### (1) Initialize a layout
layout = QgsPrintLayout(project)
layout.setName(layout_name)
layout.initializeDefaults() 
layout_manager.addLayout(layout)
iface.openLayoutDesigner(layout)

### (2) Add new page (2nd page)
page = QgsLayoutItemPage(layout)
page.setPageSize('A4', QgsLayoutItemPage.Landscape)
layout.pageCollection().addPage(page)

### (3) Add items to the layout (using 'layout')
label = QgsLayoutItemLabel(layout)
label.setText("TEST")
label.attemptMove(QgsLayoutPoint(10, 230, 0))
label.attemptResize(QgsLayoutSize(10, 10, 0))
# ADD ITEM
layout.addLayoutItem(label) 
###

For example, the coordinates would be (10, 230) to add a label to the 2nd page for a A4 landscape size 297x210 mm (see the image).

230 = 210 (height of the 1st page) + 
      10  (space between pages) +
      10  (y value for the label in the 2nd page)

enter image description here

But I want to add items using QgsLayoutItemPage object so that I don't have to deal with calculating the layout coordinates as in this answer.

I would like to follow this way:

  1. Initialize a layout,
  2. Create new page, don't add to the layout,
  3. Add items to the page and
  4. Add the page to the layout

How can I do that?

Best Answer

You should create the layout but according to the documentation you can use the page argument in the attemptMove method. So you can refer to the relative position on the corresponding layout page.

Something like this :

label.attemptMove(QgsLayoutPoint(10, 10, 0), page=1) #0 indexed, page=1 is the second page

Documentation