1

I have tried to set the legend style but all methods I had tried were error, there is one example I tried to change the font style of legend:

legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
legend.style().setFont(QFont("Microsoft JhengHei",14,1,False))

layerTree = QgsLayerTree()
layerTree.addLayer(layer)
legend.model().setRootGroup(layerTree)
basicSettings = QgsLegendBasicSettings()
basicSettings.setFont(QFont("Arial", 10))
legend.model().setBasicSettings(basicSettings)

And then it showed the error as below:

TypeError: QgsLayoutItemLegend.style(): not enough arguments

I also read the QGIS document of the rules of code, however I cannot understand the format such as the example shown below:

 setStyleFont(...)
       setStyleFont(self, component: QgsLegendStyle.Style, font: QFont)
       Sets the style ``font`` for a legend ``component``.

Would anyone elaborate its meaning and provide an example, so that I can solve the similar problems after that?

1 Answer 1

5

You must specify which part of the legend you want the text style to be applied to. For example, QgsLegendStyle.Title applies the style to the title.

manager = QgsProject.instance().layoutManager()
layout = manager.layoutByName("LAYOUT_NAME")

legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")

### USE THIS STRUCTURE
style = QgsLegendStyle()  # make new style
style.setFont(QFont("Microsoft JhengHei",30,1,False))
# style.set...(...)
legend.setStyle(QgsLegendStyle.Title, style) # set style to the legend
###

layout.addLayoutItem(legend)

Other components of legend

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.