I have created an Action that downloads a map sheet. It appears as a 'Multiband Colour' but I need it to appear using 'Paletted/Unique values'. I assume I need to add QgsPalettedRasterRenderer within the Python on my Action. How would I do that?

from qgis.utils import iface

baseurl = 'URL'
filename = "[% "LINK" %]"
path = f"/vsicurl/{baseurl}{filename}"

1 Answer 1


I have not tested this inside an action, but here is a short recipe to create a QgsPalettedRasterRenderer and apply it to a raster layer. The only slightly tricky part is creating the color ramp. I think the easiest way is to retrieve a properties map from an existing color ramp. For example, if you set up your raster symbology the way you want it via the gui, you can retrieve the properties of the color ramp by running:


You can copy this properties map and use it to construct a color ramp object in your action code.

The example below constructs a spectral (blue-red) color ramp.

Try something like:

from qgis.utils import iface
from qgis.core import QgsGradientColorRamp, QgsPalettedRasterRenderer

baseurl = 'URL'
filename = "[% "LINK" %]"
path = f"/vsicurl/{baseurl}{filename}"
layer = iface.addRasterLayer(path)

# define a dictionary of color ramp properties
# this can be retrieved from an existing styled raster layer with:
# print(iface.activeLayer().renderer().sourceColorRamp().properties())
props = {'color1': '43,131,186,255',
        'color2': '215,25,28,255',
        'discrete': '0',
        'rampType': 'gradient',
        'stops': '0.25;171,221,164,255:0.5;255,255,191,255:0.75;253,174,97,255'

# Create a gradient color ramp from the properties dictionary
color_ramp = QgsGradientColorRamp().create(props)

# Construct a class data list, passing in QgsRasterInterface object, band number & color ramp
classes = QgsPalettedRasterRenderer.classDataFromRaster(layer.dataProvider(), 1, color_ramp)
# Construct the renderer object, passing in QgsRasterInterface object, band number & class list
renderer = QgsPalettedRasterRenderer(layer.dataProvider(), 1, classes)
# Set renderer to layer

Shown below is the resulting symbology applied to a SRTM DEM raster:

enter image description here

  • Thanks for the comprehensive answer. I played around with the code some more without solving the problem. What I did do as a work around was re-proecess the COG's as a 24bit image and that solved the problem. Jul 25, 2021 at 12:31
  • Nice one! Glad you solved your problem.
    – Ben W
    Jul 25, 2021 at 13:18

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.