2

I am facing a problem with the Layout API while implementing a plugin for QGIS 3. I created a layout template , which contains different elements like map, labels, legend and scale-bar. I'd like to place my legend on the bottom of the page. But the size of the legend can change. So I wanted to place my legend using :

legend = QgsLayoutItemLegend(layout)
legend.setLinkedMap(map)
legend.setReferencePoint(QgsLayoutItem.LowerLeft)
legend.attemptMove(QgsLayoutPoint(page.pageSize().width()*0.79,page.pageSize().height()),useReferencePoint=True)

But this is not working and it gaves me the same result as without the setReferencePoint. So does anyone know why is the "LowerLeft" not working ?

A solution to my problem would be to get the height of my legend and place it from the default UpperLeft position, but I wasn't able to find out how to get that. Any idea on how to get the size of an item ?

0

2 Answers 2

2

Using an existing legend, I'm able to move the legend according to the reference point (try using the following code)

project = QgsProject.instance()
manager = project.layoutManager()
layout = manager.layoutByName('your_layout')
# Don't forget to select your legend
legend = layout.selectedLayoutItems()[0]

legend.setReferencePoint(QgsLayoutItem.LowerLeft)
print(legend.pagePositionWithUnits())
legend.attemptMove(QgsLayoutPoint(100, 200),useReferencePoint=True)
print(legend.pagePositionWithUnits())

legend.setReferencePoint(QgsLayoutItem.UpperRight)
print(legend.pagePositionWithUnits())
legend.attemptMove(QgsLayoutPoint(100, 200),useReferencePoint=True)
print(legend.pagePositionWithUnits())

Conclusion: you need to do add layout.addLayoutItem(legend) BEFORE running legend.attemptMove(... (or legend.attemptResize(...) as you need a reference point relative to the layout. It's not possible when the item has not been added to the layout.

No final conclusion at the moment as it's a refresh/timing issue e.g https://gist.github.com/ThomasG77/d15771bb30c231166701cf31788f8a6b#file-pyqgis-371225-py-L26

For the 2nd question within the first one e.g

Any idea on how to get the size of an item ?

Use

legend.sizeWithUnits()

Unfortunately, works when you run it standalone in the PyQGIS console not when using script in the above GIST.

0

to change reference point of an item in the layout. for your example, you need to replace

legend.setReferencePoint(QgsLayoutItem.LowerLeft)

with :

legend.setReferencePoint(6) # 6 is for the lowerLeft position 

you can change 6 with 0 to 8 with 0 for upperLeft(default reference point) / 4 : Middlecenter / 8 : LowerRight

Your Answer

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

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