0

I want to modify the color ramp of my layer in pyQGIS like I would do it in the layer properties :

color ramp in QGIS style

I identified QgsGraduatedSymbolRenderer().updateColorRamp(ramp=color_ramp) as the function to update it, but I can't link it to my maplayer. How can I access the renderer of a layer ?

3
  • Assuming you have a reference to a layer such as lyr, you can call the renderer with: r = lyr.renderer()
    – Matt
    Oct 25, 2022 at 15:08
  • and then I can apply the updateColorRamp on it ? Because QgsFeatureRenderer doesn't seem to have such function
    – dmjf08
    Oct 25, 2022 at 15:36
  • Take a look at this answer. Hopefully, it will point you in the right direction.
    – Matt
    Oct 25, 2022 at 15:54

1 Answer 1

1

Thanks to Matt, I got the working code :

renderer = mylayer.renderer()
if isinstance(renderer, QgsGraduatedSymbolRenderer):
    if color_ramp is None:
        default_style = QgsStyle().defaultStyle()
        color_ramp = default_style.colorRamp('Spectral')  # Spectral color ramp
        color_ramp.invert()
    renderer.updateColorRamp(ramp=color_ramp)

    if myfield is not None:
        renderer.setClassAttribute(myfield)
        mylayer.setRenderer(renderer)
        mylayer.triggerRepaint()

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.