3

I have a vector layer in QGIS. I have added a bunch of rule for this layer. This is the QDockWidget for layer in QGIS main window.

rule

So each of interstate, divided, secondary is different rule added using QgsRuleBasedRendererV2.

All the rule have the check box where I can manually toggle the visibility of the layer. Is there any way I can toggle this using python?

I tried to use layer tree

root = QgsProject.instance().layerTreeRoot()
for child in root.children():
    print type(child), child.layerName(), child.children()

but child.children is returning empty list instead of those rules.

Type of Road Network is qgis._core.QgsLayerTreeLayer.

2 Answers 2

2

This is a property of the layer, not of the layer tree.

Get the layer, and modify its renderer's rules

# A list of the layers' rules
rules = layer.rendererV2().rootRule().children()
# Deactivate a rule (in this example the first rule [0])
rules[0].setCheckState(False)
# Synchronize the legend with the symbology
iface.layerTreeView().refreshLayerSymbology(layer.id())
2
  • I tried to do this but this silently disable the rule and the checkbox status does not changes Oct 6, 2015 at 12:34
  • This is only a repainting issue. Fix added to the answer Oct 6, 2015 at 12:44
0

Accepted answer works in QGIS 2.0.

For 3.0, you must invoke setActive on the rule

rules = layer.render().rootRule().children()
rules[0].setActive(False)
iface.layerTreeView().refreshLayerSymbology(layer.id())

Your Answer

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

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