Saturday, 24 January 2015

pyqgis - refreshLayerSymbology raster layer legend


When I modify raster colors with PyQGIS, the legend in the layout layer is not update (color and value). The function refreshLayerSymbology() in my code don't do the job.


enter image description here


I had try this :


# BBOX
extent = box
# acces données

provider = self.MNT.dataProvider()
stats = provider.bandStatistics(1, QgsRasterBandStats.All, extent, 0)

if (stats.minimumValue < 0):
min = 0

else:
min = stats.minimumValue
max = stats.maximumValue
range1 = max - min

add = range1 // 2
interval = min + add

colDic = {'red': '#ff0000', 'yellow': '#ffff00', 'blue': '#0000ff'}

valueList = [min, interval, max]

lst = [QgsColorRampShader.ColorRampItem(valueList[0], QColor(colDic['blue'])),
QgsColorRampShader.ColorRampItem(valueList[1], QColor(colDic['yellow'])),
QgsColorRampShader.ColorRampItem(valueList[2], QColor(colDic['red']))]


myRasterShader = QgsRasterShader()
myColorRamp = QgsColorRampShader()

myColorRamp.setColorRampItemList(lst)
myColorRamp.setColorRampType(QgsColorRampShader.INTERPOLATED)
myRasterShader.setRasterShaderFunction(myColorRamp)

myPseudoRenderer = QgsSingleBandPseudoColorRenderer(self.MNT.dataProvider(),
self.MNT.type(),

myRasterShader)
# Add
self.MNT.setRenderer(myPseudoRenderer)

# Refresh the canvas and the legend
self.MNT.triggerRepaint()
#self.iface.mapCanvas().refresh()
self.iface.legendInterface().refreshLayerSymbology(self.MNT)

However when I use the function refreshLayerSymbology() with grayscale color, the function work.



enter image description here


The code I used is :


myGrayRenderer = QgsSingleBandGrayRenderer(self.MNT.dataProvider(), 1)

self.MNT.setRenderer(myGrayRenderer)

renderer = self.MNT.renderer()
# acces données
provider = self.MNT.dataProvider()


layer_extent = self.MNT.extent()
uses_band = renderer.usesBands()

myType = renderer.dataType(uses_band[0])

stats = provider.bandStatistics(uses_band[0],
QgsRasterBandStats.All,
layer_extent,
0)


myEnhancement = QgsContrastEnhancement(myType)
contrast_enhancement = QgsContrastEnhancement.StretchToMinimumMaximum

myEnhancement.setContrastEnhancementAlgorithm(contrast_enhancement, True)
myEnhancement.setMinimumValue(stats.minimumValue)
myEnhancement.setMaximumValue(stats.maximumValue)

self.MNT.renderer().setContrastEnhancement(myEnhancement)

# Refresh the canvas and the legend

self.MNT.triggerRepaint()
self.iface.legendInterface().refreshLayerSymbology(self.MNT)


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...