Skip to content

Instantly share code, notes, and snippets.

@sickel
Last active October 7, 2024 10:42
Show Gist options
  • Save sickel/e4cf6613aabdc9f98fe76cb93bde60b6 to your computer and use it in GitHub Desktop.
Save sickel/e4cf6613aabdc9f98fe76cb93bde60b6 to your computer and use it in GitHub Desktop.
Turn on or off rendering of categories in a QGIS categorized layer
def rendercats(searchstring):
layer = iface.activeLayer()
renderer = layer.renderer()
categories = renderer.categories()
new_renderer = QgsCategorizedSymbolRenderer(attrName=renderer.classAttribute())
for cat in categories:
value = cat.value()
if value is None:
cat.setRenderState(False)
else:
m = re.search(searchstring,value)
cat.setRenderState(m is not None )
new_renderer.addCategory(cat)
layer.setRenderer(new_renderer)
@sickel
Copy link
Author

sickel commented Oct 7, 2024

Error "AttributeError: 'NoneType' object has no attribute 'renderer'" means that no layer is currently selected. Click the selected layer and rerun

@sickel
Copy link
Author

sickel commented Oct 7, 2024

Searchstring can be any regex. The simplest will just be a string, then if that string with matching case is in the categorization value, that category will be rendered. Start the string with ^ to anchor the search to the start, end with a $ to anchor it at the end. Search python re for other possibilities.

@sickel
Copy link
Author

sickel commented Oct 7, 2024

Layer has to be rendered with Categorized Symbology

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment