Skip to content

Instantly share code, notes, and snippets.

@filipkral
Created March 16, 2026 10:24
Show Gist options
  • Select an option

  • Save filipkral/04b6dcc61248b7ae6d6e69785002497a to your computer and use it in GitHub Desktop.

Select an option

Save filipkral/04b6dcc61248b7ae6d6e69785002497a to your computer and use it in GitHub Desktop.
Prune QGIS Legend items depending on presence of features in a layer
# Update legend so it contains only Types present in the layer.
# This script detaches the legend from automatic updates!
# Change parameters to match the layer name, print_layout name, and the id of the legend element in the print layout
layer_name = "PLOCHY S ROZDÍLNÝM ZPŮSOBEM VYUŽITÍ"
layout_name = 'Layout 1'
legend_id = "Legend"
field_name = 'Typ'
project = QgsProject.instance()
layer = project.mapLayersByName()[0]
layout = project.layoutManager().layoutByName(layout)
legend = layout.itemById(legend_id)
# Detach legend from automatic project layer tree updates
legend.setAutoUpdateModel(False)
model = legend.model()
root = model.rootGroup()
# Remove existing legend items safely
for child in list(root.children()):
root.removeChildNode(child)
# --- collect existing Typ values in the dataset ---
existing_values = set()
for f in layer.getFeatures():
val = f[field_name]
if val is not None:
existing_values.add(str(val))
# --- get renderer ---
renderer = layer.renderer()
if not isinstance(renderer, QgsRuleBasedRenderer):
raise Exception("Layer must use a rule-based renderer")
root_rule = renderer.rootRule()
valid_rules = []
# --- check rules ---
for rule in root_rule.children():
expr = rule.filterExpression()
if not expr:
continue
# extract Typ value from expression
try:
typ = expr.split('and')[0].split('=')[1].strip().replace("'", "")
except Exception:
continue
if typ in existing_values:
valid_rules.append(rule)
# --- add filtered legend items ---
layer_node = QgsLayerTreeLayer(layer)
root.addChildNode(layer_node)
legend_layer_node = model.findLayer(layer.id())
for rule in valid_rules:
node = QgsLayerTreeModelLegendNode(layer_node, rule)
legend_layer_node.addLegendNode(node)
# refresh legend
legend.refresh()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment