I am in the process of creating a script which needs to add a caption to an already existing layout.

So I created a PyQGIS code in order to do it :

legend = QgsLayoutItemLegend(layout)
legend.setLinkedMap(map) # pass a QgsLayoutItemMap object


legend.attemptMove(QgsLayoutPoint(3.5, 12, QgsUnitTypes.LayoutMillimeters))
legend.attemptResize(QgsLayoutSize(5.5, 2, QgsUnitTypes.LayoutCentimeters))



The legend is displayed well but I would like there to be space before the different groups of the legend.

I saw that this was possible in the layout editor (screenshot) but after studying the documentation for QgsLayoutItemLegend, I can't find a "setSpacingAboveGroups()" method that would allow this value to be modified. (setSpacingAboveGroups does not exist, this is an example)

enter image description here

How can I change the distance between groups in the legend using PyQGIS?


You should use rstyle method of legend. It returns reference to QgsLegendStyle object for legend components. Then, you can add spacing using setMargin function. Documentation for rstyle and setMargin.

legend.rstyle(QgsLegendStyle.Group).setMargin(QgsLegendStyle.Top, 10) # Top side, 10 mm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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