1

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?

1 Answer 1

1

You can use the setStyleFont() method of the QgsLayoutItemLegend class. The first argument is a component, so you need to pass a QgsLegendStyle::Style enumerator item, e.g. QgsLegendStyle.Title, QgsLegendStyle.SymbolLabel etc.

Example snippet:

item_font = QFont('Arial', 14)
legend_item.setStyleFont(QgsLegendStyle.SymbolLabel, item_font)
legend_item.refresh()

Note that according to the docs, this method is deprecated and from version 3.30 onwards, you should

use QgsLegendStyle::setTextFormat() from style() instead.

Example below. FYI, with this approach I found it necessary to add a call to legend_item.setStyleMargin() because, for some reason, the space between the symbol and label is lost which may be a bug, but I don't have time to investigate further right now.

# >= 3.30
legend_style = QgsLegendStyle()
text_format = QgsTextFormat()
item_font = QFont('Arial')
text_format.setFont(item_font)
text_format.setSize(14)
legend_style.setTextFormat(text_format)
legend_item.setStyle(QgsLegendStyle.SymbolLabel, legend_style)
legend_item.setStyleMargin(QgsLegendStyle.Symbol, QgsLegendStyle.Right, 2.5)
legend_item.refresh()

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.