5

I create rules with this code but it creates one more but without data and when using root_rule.removeChildAt (0) it deletes a correct one.

layer = iface.activeLayer()
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
renderer = QgsRuleBasedRenderer(symbol)

def rule_based_style(layer, symbol, renderer, label, expression, color):
    root_rule = renderer.rootRule()
    rule = root_rule.children()[0].clone()
    rule.setLabel(label)
    rule.setFilterExpression(expression)
    rule.symbol().setColor(QColor(color))
    # append the rule to the list of rules
    root_rule.appendChild(rule)
    #delete the default rule[![remove 2 rules][1]][1]
    root_rule.removeChildAt(0)
    layer.setRenderer(renderer)    
    layer.triggerRepaint()

    iface.layerTreeView().refreshLayerSymbology(layer.id())

#rule_based_style(layer, symbol, renderer, 'Para Campo', ' \"REVISION\" = \'Para Campo\' ', 'yellow')
rule_based_style(layer, symbol, renderer, 'Para Campo', ' \"REVISION\" = \'Para Campo\' ', 'yellow')
rule_based_style(layer, symbol, renderer, 'De Campo NA NULL', ' \"REVISION\" = \'De Campo\' or \"REVISION\" = \'De Campo\' or \"REVISION\" IS NULL ', 'green')


6
  • First, use the method to add rules to renderer and don't use removeChildAt(0) within the method.
  • After adding the rules, remove the first child of renderer.
  • Then set layer renderer.
  • You don't need to define parameters for layer, symbol and renderer in method definition.
  • You don't need " in expression for field names.
layer = iface.activeLayer()
symbol = QgsSymbol.defaultSymbol(layer.geometryType())
renderer = QgsRuleBasedRenderer(symbol)

def add_rule_to_renderer(label, expression, color):
    rule = renderer.rootRule().children()[0].clone()
    rule.setLabel(label)
    rule.setFilterExpression(expression)
    rule.symbol().setColor(QColor(color))
    renderer.rootRule().appendChild(rule)

add_rule_to_renderer('Para Campo', "REVISION='Para Campo'", 'yellow')
add_rule_to_renderer('De Campo NA NULL', "REVISION='De Campo' or REVISION IS NULL", 'green')

# remove first child
renderer.rootRule().removeChildAt(0)

layer.setRenderer(renderer)    
layer.triggerRepaint()

iface.layerTreeView().refreshLayerSymbology(layer.id())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.