How do I set layer transparency in QGIS 2.0 with Python?

I found a plugin called rasparenza today that got me going on the transparency issue.

For QGIS 2.x it looks like we want the setOpacity() method:

rlayer = qgis.utils.iface.activeLayer()

# Set opacity
rlayer.renderer().setOpacity(0.5)

# Trigger a repaint
if hasattr(rlayer, "setCacheImage"):
    rlayer.setCacheImage(None)
rlayer.triggerRepaint()

For some reason, I thought I should be able to use iface.mapCanvas().refresh() but it didn't seem to do the refresh.


This way you can access current list of transparency values:

rt=l.rasterTransparency()
lst = rt.transparentSingleValuePixelList()
for item in lst: print item.pixelValue, item.percentTransparent

...

-9999.0 100.0

0.0 50.0

To set a list with just one value:

x = QgsRasterTransparency.TransparentSingleValuePixel()
x.pixelValue = 123
x.transparencyPercent = 50
rt.setTransparentSingleValuePixelList( [ x ] )

The above examples suppose that you use single band raster. In case of RGB image the steps are similar, just instead of "SingleValue" methods you would use "ThreeValue" methods and instead of "pixelValue" attribute there are "red", "green", "blue" attributes.


Perhaps more updated answer from Rob Lodge

from qgis.core import QgsRasterTransparency

print 'Start'
active_layer = l = qgis.utils.iface.mapCanvas().currentLayer()
raster_transpareny  = active_layer.renderer().rasterTransparency()
ltr = QgsRasterTransparency.TransparentSingleValuePixel()
tr_list = []
ltr.min = 0  # Or another value
ltr.max = 0  # Or another value
ltr.percentTransparent = 100  # Or another value
tr_list.append(ltr)  # You can add more item in this list.
active_layer.renderer().rasterTransparency().setTransparentSingleValuePixelList(tr_list)

active_layer.triggerRepaint()  # Tried with iface.mapCanvas().refresh(), but it didn't work
print 'Finish'

You can try this in QGIS Python Console. I tried with QGIS 2.8.3