6

How do I remove unwanted colour from the palette from a Raster via the PyQGIS API? For example, remove black from the palette. It works manually within Layer Properties -> Symbology -> Band Rendering -> Paletted.

I have looked in 3.10 API docs but can't see how this is done.

https://qgis.org/pyqgis/3.10/core/QgsPalLayerSettings.html

3

1 Answer 1

9
  • Get palette values

    classes = layer.renderer().classes()
    
  • Remove any class

    del classes[0] # removes the first item
    
  • Set layer renderer

    renderer = QgsPalettedRasterRenderer(provider, band, classes)
    layer.setRenderer(renderer)
    

Minimal sample code:

layer = iface.activeLayer()

renderer = layer.renderer()

provider = layer.dataProvider()
band = renderer.band()    
classes = renderer.classes()
del classes[0]  # remove the first color

renderer = QgsPalettedRasterRenderer(provider, band, classes)

layer.setRenderer(renderer)
layer.triggerRepaint()
1
  • Many thanks, that works
    – Den15
    Commented Apr 22, 2023 at 13:06

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.