I try to set style settings in QGIS 2.18. However I get QColor
error. Here is my code:
layer = iface.activeLayer()
layer.setDrawingStyle('SingleBandPseudoColor')
stats = layer.dataProvider().bandStatistics(1, QgsRasterBandStats.Min | QgsRasterBandStats.Max)
minVal = int(stats.minimumValue + 0.5)
maxVal = int(stats.maximumValue + 0.5)
mean = (minVal + maxVal) / 2
s1 = str((minVal * 2 + maxVal) / 3)
s2 = str((minVal + maxVal * 2) / 3)
item0 = QgsColorRampShader.ColorRampItem(minVal, QColor(10, 100, 10), str(minVal) + ' - ' + s1)
item1 = QgsColorRampShader.ColorRampItem(mean, QColor( 153, 125, 25), s1 + ' - ' + s2)
item2 = QgsColorRampShader.ColorRampItem(maxVal, QColor(255, 255, 255), s2 + ' - ' + str(maxVal))
fcn = QgsColorRampShader(minVal, maxVal)
fcn.setColorRampType(QgsColorRampShader.INTERPOLATED)
fcn.setColorRampItemList([item0, item1, item2])
layer.renderer().shader().setRasterShaderFunction(fcn)
layer.triggerRepaint()
The error is:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "c:/users/mustaf~1/appdata/local/temp/tmpippgsf.py", line 10, in <module>
item0 = QgsColorRampShader.ColorRampItem(minVal, QColor(10, 100, 10), str(minVal) + ' - ' + s1)
NameError: name 'QColor' is not defined
Best Answer
You need to import classes before you can use them. At the top of your script put
or
if you want to import all the classes at once