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:
- Initialize a layout,
- Add new page (2nd page) and
- 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)
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:
- Initialize a layout,
- Create new page, don't add to the layout,
- Add items to the page and
- 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 theattemptMove
method. So you can refer to the relative position on the corresponding layout page.Something like this :
Documentation