Last active
October 7, 2024 10:42
-
-
Save sickel/e4cf6613aabdc9f98fe76cb93bde60b6 to your computer and use it in GitHub Desktop.
Turn on or off rendering of categories in a QGIS categorized layer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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.
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
Error "AttributeError: 'NoneType' object has no attribute 'renderer'" means that no layer is currently selected. Click the selected layer and rerun