QGIS – Implement Rule Based Rendering in QGIS Effectively

cfilterqgisrule-based

I am looking for an example of how to use the QgsRuleBasedRendererV2 to filter features of a layer based on an attribute value (0 or 1). Has anyone done this in Python or C++?

Best Answer

This is an example of Python Code:

from PyQt4.QtGui import *

# define some rules: label, expression, color name, width
my_rules = (
    ('Feature one', '"type" LIKE \'first\'', 'green', 2),
    ('Feature two', '"type" LIKE \'second\'', 'red', 2),
    ('Feature three', '"type" LIKE \'third\'', 'blue', 2),
)

layer = iface.activeLayer()

# create a new rule-based renderer
symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
renderer = QgsRuleBasedRendererV2(symbol)

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

for label, expression, color_name, width in my_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))
    rule.symbol().setWidth(width)
    # 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.setRendererV2(renderer)

iface.mapCanvas().refresh()

I tested it with this line vector layer ('expression' in field 'type'):

enter image description here

After run the code in the Python Console of QGIS (line2 as Active Layer):

enter image description here

Related Question