11

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.

10
+50

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'
2

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

  • 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.