1

I have a vector layer. It's defined with rule based labeling.

I need to control the rules to turn on / off programmatically.

How to do it?

enter image description here

1 Answer 1

2

Using QGIS 3.28 on a layer that already has rule based labeling active, this works:

layer = iface.activeLayer()
ruleList = layer.labeling().rootRule().children()
for rule in ruleList:
    if rule.description() == 'my description':  # the description you set for the rule
        rule.setActive(False)  # False turns rule off, True turns rule on
layer.triggerRepaint()

If you didn't set a description for all rules, you could also check the filter expression:

if rule.filterExpression() == '"feed_type" = 2':
    rule.setActive(False)

Another approach could be to use the unique rule identifier obtained by ruleKey() on the Rule itself, save a reference to it somewhere and use it later to find the rule again using findRuleByKey(), but I haven't tested it. If you would like to dig into it, check out the API for QgsRuleBasedLabeling

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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