I'm trying to change the color ramp for a raster layer using PyQGIS.
What I have works, but the layer doesn't redraw. However, if I open the layer properties and click "Apply", the map redraws.
I've called both triggerRepaint
and iface.mapCanvas().refresh()
, both which are not producing the expected result.
plugin
from qgis.PyQt import QtWidgets, QtGui, QtCore
# do this otherwise you have to constantly declare the class you want
# to use
import qgis
class MyTool:
def __init__(self, iface):
self.iface = iface
self.canvas = self.iface.mapCanvas()
def initGui(self):
self.action = QtWidgets.QAction("My Tool", self.iface.mainWindow())
self.action.setObjectName("MyToolAction")
self.action.setWhatsThis("Configuration for My Tool")
self.action.setStatusTip("This is status tip")
self.action.triggered.connect(self.run)
self.iface.addToolBarIcon(self.action)
self.iface.addPluginToMenu("&My Tool", self.action)
def unload(self):
self.iface.removePluginMenu("&My Tool", self.action)
self.iface.removeToolBarIcon(self.action)
def run(self):
# not my actual file, but one which seems to reproduce the problem
path = "/vsicurl/http://oin-hotosm.s3.amazonaws.com/59d33df023c8440011d7b26d/0/b378087a-c2a5-43a0-abec-71fcfb051150.tif"
layer_intensity = self.iface.addRasterLayer(path, 'intensity')
color_ramp = qgis.core.QgsStyle().defaultStyle().colorRamp('Viridis')
ramp_shader = qgis.core.QgsColorRampShader(1, 255, color_ramp)
raster_shader = qgis.core.QgsRasterShader()
raster_shader.setRasterShaderFunction(ramp_shader)
renderer = qgis.core.QgsSingleBandPseudoColorRenderer(layer_intensity.dataProvider(), 1, raster_shader)
layer_intensity.setRenderer(renderer)
layer_intensity.triggerRepaint()
self.iface.mapCanvas().refresh()
metadata
[general]
name=My Tool
[email protected]
author=dood
qgisMinimumVersion=3.10
description=My Tool
about=Software for stuff
version=version 0.1
repository=http://www.itopen.it/repo
experimental=True