8

I have a raster layer loaded in QGIS 2.0 and I'd like to be able to set its transparency via the Python console. I'm new to the API and have not been able to find out how to do this.

Here's what I see from the console:

>>> l = qgis.utils.iface.activeLayer()
>>> l
<qgis.core.QgsRasterLayer object at 0x07144DF8>
>>> rt = l.rasterTransparency()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: 'QgsRasterLayer' object has no attribute 'rasterTransparency'

I'm just loading a single band raster in GeoTiff format with a palleted color scheme... nothing too fancy.

Am I getting the layer incorrectly?

3 Answers 3

10

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.

3

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.

0
2

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

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.