3

I'm developing a script which includes a function to style raster layers (based on Setting 'classificationMode = Continuous' to a raster layer using PyQGIS? and Qgis: style a discrete raster). The script executes without any errors and colours the layer correctly. But the styled raster does not show any value labels (see image below).

If I go to the Style tab in Layer Properties and click apply, the values are then shown, so I think I must just be missing some sort of refresh command. My understanding was that lyr.triggerRepaint() should take care of this issue. I also tried iface.mapCanvas().refresh() but no such luck.

styled layer output

def styleRaster(lyr, lst):
    fcn = QgsColorRampShader()
    fcn.setColorRampType(QgsColorRampShader.INTERPOLATED)
    fcn.setColorRampItemList(lst)
    shader = QgsRasterShader()
    shader.setRasterShaderFunction(fcn)
    renderer = QgsSingleBandPseudoColorRenderer(lyr.dataProvider(), 1, shader)
    lyr.setRenderer(renderer)
    lyr.triggerRepaint() 
    return


tciLyr = iface.addRasterLayer(hydroLyrs['tci'])

lst = [QgsColorRampShader.ColorRampItem(0, QColor("#f7fbff")),\
    QgsColorRampShader.ColorRampItem(4, QColor("#deebf7")),\
    QgsColorRampShader.ColorRampItem(8, QColor("#c6dbef")),\
    QgsColorRampShader.ColorRampItem(12, QColor("#9ecae1")),\
    QgsColorRampShader.ColorRampItem(16, QColor("#6baed6")),\
    QgsColorRampShader.ColorRampItem(20, QColor("#4292c6")),\
    QgsColorRampShader.ColorRampItem(24, QColor("#2171b5")),\
    QgsColorRampShader.ColorRampItem(28, QColor("#08519c")),\
    QgsColorRampShader.ColorRampItem(32, QColor("#08306b"))]

styleRaster(tciLyr, lst)
  • How about iface.legendInterface().refreshLayerSymbology(lyr)? – Joseph Jan 10 '18 at 11:20
  • thanks @Joseph but that did not work for me either. I still get the same output – firefly-orange Jan 10 '18 at 11:34
3

I fixed this by adding the value label to the colourRampItem. My input list now looks like this:

lst = [QgsColorRampShader.ColorRampItem(0, QColor("#f7fbff"),'0'),\
    QgsColorRampShader.ColorRampItem(4, QColor("#deebf7"),'4'),\
    QgsColorRampShader.ColorRampItem(8, QColor("#c6dbef"),'8'),\
    QgsColorRampShader.ColorRampItem(12, QColor("#9ecae1"),'12'),\
    QgsColorRampShader.ColorRampItem(16, QColor("#6baed6"),'16'),\
    QgsColorRampShader.ColorRampItem(20, QColor("#4292c6"),'20'),\
    QgsColorRampShader.ColorRampItem(24, QColor("#2171b5"),'24'),\
    QgsColorRampShader.ColorRampItem(28, QColor("#08519c"),'28'),\
    QgsColorRampShader.ColorRampItem(32, QColor("#08306b"),'32')]

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.