3

Is there a PyQGIS code to edit the transparency of rule based symbols?

enter image description here

Taras
35.8k5 gold badges77 silver badges152 bronze badges
asked Oct 11, 2022 at 13:38
1

1 Answer 1

5

As described in the @wanderzen's comment to this question you can use setOpacity() to change the transparency of a symbol.

Symbols themselves can be accessed from each of the rules (QgsRuleBasedRenderer::Rule) stored by the QgsRuleBasedRenderer as children of the invisible root rule.

An example to set all all rules to 75% opacity would be:

layer = iface.activeLayer()
root_rule = layer.renderer().rootRule()
for rule in root_rule.children():
 rule.symbol().setOpacity(0.75)
 
layer.triggerRepaint()
Taras
35.8k5 gold badges77 silver badges152 bronze badges
answered Oct 12, 2022 at 18:07
4
  • I don't manage to make your code work. I get this error: 'QgsSingleSymbolRenderer' object has no attribute 'rootRule' Commented Mar 1, 2023 at 16:27
  • @zakros This question is about changing opacity of the individual symbols of a rule based renderer. If you are using a single symbol renderer you can just use layer.setOpacity(0.75) Commented Mar 1, 2023 at 19:08
  • Thanks for answering me. Yes but if I use setOpacity I can't change the opacity of only the selectedFeatures Commented Mar 1, 2023 at 20:34
  • I tried this: vlayer = iface.activeLayer() vlayer.selectByExpression('"field_A"= \'category_FZ15\'', QgsVectorLayer.SetToSelection) vlayer.selectedFeatures()[0].setOpacity(1) ` But I get this: AttributeError: 'QgsFeature' object has no attribute 'setOpacity' Commented Mar 2, 2023 at 9:36

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.