13

With the following code I can set 100% transparency to raster value 0:

map=None

for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
  if lyr.name() == "some_layer":
    map= lyr

tr=None

tr=QgsRasterTransparency()
tr.initializeTransparentPixelList(0)
map.renderer().setRasterTransparency(tr)
map.triggerRepaint()

How can I define two values (0 and 8) to be 100% transparent?

When I repeat the commands of the last block with raster value 8, the first value (0) is removed from the layer transparency.

BritishSteel
  • 6,637
  • 4
  • 38
  • 64
Stefan
  • 4,414
  • 1
  • 33
  • 66

2 Answers2

12

I found this other thread which was helpful How do I set layer transparency in QGIS 2.0 with Python? It seems like there should be a shorter and more efficient way, but I tested this and it works:

print 'Start'
active_layer = qgis.utils.iface.mapCanvas().currentLayer()
raster_transparency  = active_layer.renderer().rasterTransparency()
ltr = QgsRasterTransparency.TransparentSingleValuePixel()
ltr2 =  QgsRasterTransparency.TransparentSingleValuePixel()
tr_list = []
ltr.min = 0  # Or another value
ltr.max = 0  # Or another value
ltr.percentTransparent = 100  # Or another value
ltr2.min = 8  # Or another value
ltr2.max = 8  # Or another value
ltr2.percentTransparent = 100
tr_list.append(ltr)
tr_list.append(ltr2)

raster_transparency.setTransparentSingleValuePixelList(tr_list)

active_layer.triggerRepaint()  # Tried with iface.mapCanvas().refresh(), but it didn't work
print 'Finish'
kflaw
  • 1,416
  • 17
  • 41
3

Is Python a requirement? If I understand what you want, you can do this in the QGIS UI, in the raster layer properties: enter image description here

Jeff G
  • 399
  • 2
  • 11
  • Yes, Python is a requirement. I've built a plugin that loads topographic maps to a QGIS project, selected from a sheet line system. – Stefan Jun 14 '16 at 17:17