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?
1 Answer 1
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
-
This might be considered a solution. But before using this, I have to add the page to the layout. I couldn't find a solution to add items to a page and add the page to the layout. This looks like the closest one.Kadir Şahbaz– Kadir Şahbaz2021年01月10日 21:15:13 +00:00Commented Jan 10, 2021 at 21:15
-
@KadirŞahbaz : I think you're have your reasons but every item depends on the layout. So since there is not setLayout to transfer an item to an other layout, your best shot is to create a layout and clone it.lejedi76– lejedi762021年01月11日 10:19:44 +00:00Commented Jan 11, 2021 at 10:19