Tuesday 21 January 2020

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



I have a raster layer loaded in QGIS 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. Any help would be greatly appreciated!


Update:


Here's what I see from the console:


>>> l = qgis.utils.iface.activeLayer()
>>> l

>>> rt = l.rasterTransparency()
Traceback (most recent call last):
File "", line 1, in
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?



Answer



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.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...