1

Is there a way to set the current raster band to an existing QgsPalettedRasterRenderer object? Other renderer have specific methods for that (e.g. setRedBand, setGreenBand, setBlueBand, setGrayBand, etc.).

For QgsPalettedRasterRenderer I haven't found anything like that. I guess it is done in a different manner (?).

renderer = layer.renderer()
assert isinstance(renderer, QgsPalettedRasterRenderer)

# Getting the current raster band is working:
print(renderer.band())  

# But how to set a new raster band? A setBand method does not exist.
renderer.setBand(band) # not working
1

Not sure if I understood your question correctly, but as I understand, QgsPalettedRasterRenderer is for single band rasters, therefore, no need to have a setBand function for it. However, you could easily apply a palette of colours to your raster even if is multi band, by:

Assumming you have all your imports done

rlayer = iface.addRasterLayer('path/to/raster', 'RasterLayerName')

Create your own list of paletted colours pcolor.

pcolor = []

pcolor.append(QgsColorRampShader.ColorRampItem(-1, QColor("#d2ca97"), '-1'))    
pcolor.append(QgsColorRampShader.ColorRampItem(0, QColor("#f7f7f7"), '0'))    
pcolor.append(QgsColorRampShader.ColorRampItem(1, QColor("#a1d99b"), '1'))    
pcolor.append(QgsColorRampShader.ColorRampItem(10, QColor("#41ab5d"), '10'))    
pcolor.append(QgsColorRampShader.ColorRampItem(25, QColor("#006d2c"), '25'))    
pcolor.append(QgsColorRampShader.ColorRampItem(50, QColor("#00441b"), '50'))

Assign the colour list to the renderer, using band=1

renderer = QgsPalettedRasterRenderer(rlayer.dataProvider(), 1, qgis.core.QgsPalettedRasterRenderer.colorTableToClassData(pcolor))

Set the renderer to your layer

rlayer.setRenderer(renderer)

trigger the repaint

rlayer.triggerRepaint()

Then you have a raster with paletted colours. Very useful for categorical values in rasters.

  • You can use QgsPalettedRasterRenderer also for multiband band rasters, e.g. using the second band of a 3 band raster should be fine. – Andreas Rabe Apr 5 at 13:25

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.