I tried to represent objects of one layer in a different colours depending on a specific attribute. So I came across the rule-based renderer and also already found an algorithm how to use it. (How to programmatically set a rule-based renderer in QGIS?).
So I tried to do it the same way but switched the Classes QgsSymbolV2 and RendererV2 to QgsSymbol and Renderer because the other ones aren't existing in QGIS3. So my script is looking like this:
road_rules = ( ('Criteria_w_h', '"type" LIKE 'Maximum'', 'red', (2,3)), ('Restriktion_h', '"type" LIKE 'Summe_2'', 'orange', (200,)), ('Restriktion_m', '"type" LIKE 'Summe_2'', 'yellow', (60,199,)), ('Restriktion_l', '"type" LIKE 'Summe_2'', 'green', (1,59,)) )
# create a new rule-based renderer
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
renderer = QgsRuleBasedRenderer(symbol)
# get the "root" rule
root_rule = renderer.rootRule()
for label, expression, color_name, scale in road_rules:
# create a clone (i.e. a copy) of the default rule
rule = root_rule.children()[0].clone()
# set the label, expression and color
rule.setLabel(label)
rule.setFilterExpression(expression)
rule.symbol().setColor(QColor(color_name))
# set the scale limits if they have been specified
if scale is not None:
rule.setScaleMinDenom(scale[0])
rule.setScaleMaxDenom(scale[1])
# append the rule to the list of rules
root_rule.appendChild(rule)
# delete the default rule
root_rule.removeChildAt(0)
# apply the renderer to the layer
layer.setRenderer(renderer)
It isn't working in this way. Does anyone have an idea what I am doing wrong?