I'm working with PyQGIS and have a function that successfully adds a legend to a QGIS composition, including layers and their symbology. However, I'm struggling to figure out how to change the font of the legend text. Below is the part of my code where I add the legend:
def add_legend_to_layout(self, layout, x, y, width, height, layer_name):
legend_item = QgsLayoutItemLegend(layout)
layout.addLayoutItem(legend_item)
# Desativar a atualização automática do modelo
legend_item.setAutoUpdateModel(False)
# Obter a árvore de camadas da legenda
legend_layer_tree = legend_item.model().rootGroup()
# Remover todas as camadas existentes
legend_layer_tree.removeAllChildren()
# Adicionar apenas a camada específica
layer = QgsProject.instance().mapLayersByName(layer_name)[0]
node_layer = QgsLayerTreeLayer(layer)
# Adicionar a camada à legenda
legend_layer_tree.addChildNode(node_layer)
# Aplicar o estilo 'Hidden' ao primeiro nó (neste caso, o nó da camada adicionada)
QgsLegendRenderer.setNodeLegendStyle(legend_layer_tree.children()[0], QgsLegendStyle.Hidden)
# Atualizar a legenda para aplicar as alterações
if( self.layer_name == "POSTES_COMAC" or self.layer_name == "POSTES_CAPFT"):
legend_item.setColumnCount(0)
else:
legend_item.setColumnCount(5)
legend_item.updateLegend()
legend_item.setSplitLayer(True)
legend_item.setColumnCount(2)
# Mover e redimensionar o item da legenda
legend_item.attemptMove(QgsLayoutPoint(x, y, QgsUnitTypes.LayoutMillimeters))
legend_item.attemptResize(QgsLayoutSize(width, height, QgsUnitTypes.LayoutMillimeters))
return legend_item
I haven't been able to find how to modify the legend's font style and size in the QGIS documentation. Does anyone know how to achieve this or can point me in the right direction?