I'm in the process of developing a plugin which highlights/changes the color of a set of features in a vector layer, depending on some calculation.

I found a nice article about QGIS – Rule based styling and i need to do the same thing but using python code.

What is the best way of doing this? Are there any examples out there?


This page has a good example of doing rule based renderer via python:

Rule-based renderer

The rule-based renderer styles features using a list of rules, defined by expressions. The rules are processed sequentially, with the first matching rule used to render a feature.

The example below defines a new rule-based renderer for different kinds of road features. Major roads are shown in orange, minor roads are shown in black at scales larger than 1:2,500 and residential roads are shown in grey at scales between 1:100 and 1:1,000.

# define some rules: label, expression, color name, (min scale, max scale)
road_rules = (
    ('Major road', '"type" LIKE \'major\'', 'orange', None),
    ('Minor road', '"type" LIKE \'minor\'', 'black', (0.0, 2500.0,)),
    ('Residential road', '"type" LIKE \'residential\'', 'grey', (100.0, 1000.0,)),

# 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, 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
    # set the scale limits if they have been specified
    if scale is not None:
    # append the rule to the list of rules

# delete the default rule

# apply the renderer to the layer
| improve this answer | |
  • How would I set the label to a field variable in the shape with a RuleBasedRenderer? – FredFury Apr 18 '16 at 9:38

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.