4

How can I set the transparency for all layers within a group of layers?

I assume this will require the use of a FOR loop in the Python Console.

Based on How to set the transparency for multiple layers or add a global transparancy preference?

I tried the following:

for layer in iface.legendInterface().layers():
   layer.renderer().setOpacity(0.5)

But I only get this error:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AttributeError: 'QgsVectorLayer' object has no attribute 'renderer'

What am I doing wrong?

1
  • 1
    'QgsVectorLayer' objects have not attribute 'renderer'. The equivalent method is layer.setLayerTransparency(50).
    – xunilk
    Commented Jun 14, 2015 at 9:57

3 Answers 3

7

As of QGIS 3.XX the given answers don't work. Also there is no mention of opacity or transparency in the documentation of QgsVectorLayer.

According to API break: https://qgis.org/api/3.0/api_break.html this is what works in QGIS 3.XX:

vlayer.setOpacity(0.5) 
4

The problem is that 'QgsVectorLayer' objects have not attribute 'renderer'. This kind of method is for raster layers. If you want to change the transparency of QgsVectorLayer objects you have to use the method: 'setLayerTransparency(int)'; located in QgsVectorLayer class.

Next code works for these kind of objects:

mc=iface.mapCanvas()

layers=[]

n = mc.layerCount()

for i in range(n):
    layers.append(mc.layer(i))

for layer in layers:

    if layer.type() == 0: #QgsVectorLayer
        layer.setLayerTransparency(95)

    else:
        layer.renderer().setOpacity(0.5)

    layer.triggerRepaint()

I tested it in QGIS. See next images (raster layer has a different projection but the transparency was also assigned):

enter image description here

enter image description here

3
  • 1
    Your example is setting transparency on many layers but not on many layers within a group.
    – artwork21
    Commented Jun 13, 2015 at 16:45
  • 1
    This no longer works in QGIS 3.XX Commented Jan 29, 2021 at 14:01
  • The link above from @joskal is no longer valid, FYI.
    – b-jazz
    Commented May 29, 2022 at 0:19
0

For qgis 3.x you may use the plugin "Group Transparency"

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.