2

I'm trying to build a layout with pyqgis and I'm not able to hide or remove the label from the caption subgroup as shown in the image below.

enter image description here

This is what I have until now:

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

legend.setAutoUpdateModel(False)
layerTree = QgsLayerTree()
layerTree.addLayer(t1_t2_total)
legend.model().setRootGroup(layerTree)

style = QgsLegendStyle()  # make new style
style.setFont(QFont("Times New Roman", 8, QFont.Bold)) 

subGroupStyle = QgsLegendStyle()  # make new style
subGroupStyle.setFont(QFont("Times New Roman", 0))
subGroupStyle.setFontColor(QColor("white"))

legend.setStyle(QgsLegendStyle.Title, style)
legend.setStyle(QgsLegendStyle.Subgroup, subGroupStyle) 
legend.setStyle(QgsLegendStyle.SymbolLabel , style)

legend.attemptMove(QgsLayoutPoint(148, 85, QgsUnitTypes.LayoutMillimeters))
legend.attemptResize(QgsLayoutSize(21, 8, QgsUnitTypes.LayoutMillimeters))
layout.addItem(legend)
...

how can I achieve this?

1 Answer 1

2

The method you are looking for is QgsLegendRenderer.setNodeLegendStyle(). The first argument is a QgsLayerTreeNode object and the second is a QgsLegendStyle.Style Enum object, e.g. QgsLegendStyle.Hidden.

Example based on your code:

layout = QgsProject.instance().layoutManager().layoutByName('Layout 1')

t1_t2_total = QgsProject.instance().mapLayersByName('your_layer_name')[0]

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

legend.setAutoUpdateModel(False)
layerTree = QgsLayerTree()
# Store a reference QgsLayerTreeLayer object returned by addLayer() method
layerTreeLayer = layerTree.addLayer(t1_t2_total)
# Add this line
QgsLegendRenderer.setNodeLegendStyle(layerTreeLayer, QgsLegendStyle.Hidden)
legend.model().setRootGroup(layerTree)

style = QgsLegendStyle()  # make new style
style.setFont(QFont("Times New Roman", 8, QFont.Bold)) 

subGroupStyle = QgsLegendStyle()  # make new style
subGroupStyle.setFont(QFont("Times New Roman", 0))
subGroupStyle.setFontColor(QColor("white"))

legend.setStyle(QgsLegendStyle.Title, style)
legend.setStyle(QgsLegendStyle.Subgroup, subGroupStyle) 
legend.setStyle(QgsLegendStyle.SymbolLabel , style)

legend.attemptMove(QgsLayoutPoint(148, 85, QgsUnitTypes.LayoutMillimeters))
legend.attemptResize(QgsLayoutSize(21, 8, QgsUnitTypes.LayoutMillimeters))
layout.addItem(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.