2

I want to add new rules for a layer. However when I add them previous one(s) are deleted. Here is my code:

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

# get the root rule
root_rule = renderer.rootRule()

# create clone of the default rule
rule = root_rule.children()[0].clone()

# set the label, expression and color
rule.setLabel("Akarsu Kutlesi")
rule.setFilterExpression(""""Subbasin" IN (2,4,6)""")
rule.symbol().setColor(QColor("orange"))

# append the rule to the list of rules
root_rule.appendtChild(rule)
# apply the renderer
layer.setRenderer(renderer)

Here is existing rules of layer:

enter image description here

enter image description here

2

Your code works fine. When you want to add a new rule, do not repeat the first 3 lines of code as this creates a new symbol renderer. Just start from

root_rule = renderer.rootRule()
...

And create your new rule.


I find it easier to use a function like the following:

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))
    root_rule.appendChild(rule)
    layer.setRenderer(renderer)
    layer.triggerRepaint()
    iface.layerTreeView().refreshLayerSymbology(layer.id())

Then you can apply new rules:

rule_based_style(layer, symbol, renderer, 'Akarsu Kutlesi', ' \"Subbasin\" IN (2,4,6) ', 'orange')
rule_based_style(layer, symbol, renderer, 'Something else', ' \"Subbasin\" IN (3,5,7) ', 'red')

Example

  • thanks for reply but I try that now and realize that previous rules are deleted. Here is the steps before code and after code respectively: imgur.com/a/pewupoO – Mustafa Uçar May 10 '18 at 6:37
  • @MustafaUçar - You are running it as a script which means every time it is run, you are creating new instances which replace everything else. The code posted should be used in the Python Console as you can define the parameters of the function. – Joseph May 11 '18 at 11:56
  • I have already tried that in python console and got that result. – Mustafa Uçar May 11 '18 at 11:59
  • @MustafaUçar - Apologies but I can't replicate your problem. It works fine for me :) – Joseph May 11 '18 at 12:05
  • Okey but can you try for me that: create a polygon shape with label - manually from QGIS- that I upload the link (first image). Then open again the project and give new rules. Previous rules are deleted (second image). – Mustafa Uçar May 11 '18 at 12:07

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.