4

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)
layout.addLayoutItem(legend)
        
legend.setLinkedMap(map) # pass a QgsLayoutItemMap object

legend.setLegendFilterByMapEnabled(True)
#legend.adjustBoxSize()
legend.setResizeToContents(False)

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

legend.setLineSpacing(15)
legend.setSymbolHeight(6)

#legend.setSpacingAboveGroups(15)

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?

5

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
                                                                 
0

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.