QGIS – Remove Empty Categories from Table of Contents

qgistable of contents

As you can see in the screenshot, I have a layer with a lot of empty categories (0 features). Is it a way to automatically remove this categories from TOC? To do it manually, it is complicated cause I have a lot of empty categories.

I don't want to reclassified, cause I don't want to lose my symbology!
enter image description here

EDIT
@Mayo:
Are you sure it works in this case? See second capture.
In case, value is the same as legend, it works… but in the capture, you'll see it is different. And after using the python code, the category is empty.
enter image description here

Best Answer

Paste this script in the python console, select the layer where you want to remove the nonexistent categories and click run.

layer = iface.activeLayer() # get the active layer
renderer = layer.renderer().clone() # get layer renderer
exp = QgsExpression(renderer.classAttribute()) # get the category expression
field_map = []
# evaluate the expression for each feature and store results in a list
for feature in layer.getFeatures():
    exp_context = QgsExpressionContext()
    exp_context.setFeature(feature)
    field_map.append(exp.evaluate(exp_context))
    
categories = renderer.categories()
for cat in categories.copy():
    if not field_map.count(cat.value()): # if there's no feature with this value
        renderer.deleteCategory(renderer.categoryIndexForValue(cat.value())) # remove the category
layer.setRenderer(renderer)
Related Question