2

I'm trying to set up a legend in the lower part of the map and I have only achieved this:

legend = QgsLayoutItemLegend(layout)
legend.model().setRootGroup(root)
layout.addLayoutItem(legend)
legend.attemptMove(QgsLayoutPoint(210, 5, QgsUnitTypes.LayoutMillimeters))

This creates the legend in the layout but I want to rotate it 270°, delete the margins around the colored rectangles, hide the subgroup's title and hide the white color of the background (so that the legend's background appears transparent). I would also like to make the reduce the Spacing between legend items to 0.05 mm and change the size of the legend rectangles. The pictures show the code result and the manually edited image.

enter image description here

enter image description here

1 Answer 1

3

I assume this answer is not a direct answer but a way to help you discover how programmatically change the layout item from PyQGIS by discovering properties you set with the GUI.

project = QgsProject.instance()
manager = project.layoutManager()
layout = manager.layoutByName('yourlayoutname')
# Select the legend layout you've set in the GUI (the one you want to achieve through PyQGIS)
legend = layout.selectedLayoutItems()[0]
legend.setAutoUpdateModel(False)
legend.setItemRotation(270)
legend.setBackgroundEnabled(True)
legend.setSymbolHeight(7.0)
legend.setSymbolWidth(7.0)

In fact, I do answer some of your requirements as the code show how to rotate, disable automatic legend, disable background, change rectangle dimensions.

Use getters documented in the API to inspect the QgsLayoutItemLegend using https://qgis.org/api/classQgsLayoutItemLegend.html#ac1842f95a9652810af008e1b3fc8d4ba, you should be able to understand how to change the other parameters you want to change.

0

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.