1

I am trying to style my vector layer in QGIS using the following python code:

layer = iface.activeLayer()
myStyle = QgsStyleV2().defaultStyle()
defaultColorRampNames = myStyle.colorRampNames()
ramp = myStyle.colorRamp(defaultColorRampNames[1])
field='count'
renderer = QgsCategorizedSymbolRendererV2(field,[])
renderer.setSourceColorRamp(ramp)

layer.setRendererV2(renderer)
if iface.mapCanvas().isCachingEnabled():
    layer.setCacheImage(None)
else:
    iface.mapCanvas().refresh()
layer.triggerRepaint()

But on executing this code , all features get coloured white.Now i know this is because i am passing an empty second argument to QgsCategorizedSymbolRendererV2(field,[]).The problem is that i am not able to figure out what to pass as the second argument if i want to use the default color ramp.

4
  • layermap = QgsMapLayerRegistry.instance().mapLayersByName(name)[0] ;)
    – Nathan W
    Aug 19, 2015 at 14:09
  • Okay ..writing the function might have been an overkill but this doesn't solve the problem i have.
    – jps
    Aug 19, 2015 at 14:11
  • It doesn't but it's just helping you write shorter code.
    – Nathan W
    Aug 19, 2015 at 14:13
  • @NathanW Shortened the code
    – jps
    Aug 19, 2015 at 14:28

1 Answer 1

1

Okay ..I figured out a way to do that .

I had to use QgsGraduatedSymbolRendererV2 rather than QgsCategorizedSymbolRendererV2

Here is the code:

layer = iface.activeLayer()
field='count'
myRenderer = QgsGraduatedSymbolRendererV2()
myRenderer.setClassAttribute(field)
myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
myRenderer.updateClasses(layer,QgsGraduatedSymbolRendererV2.EqualInterval,50)
myStyle = QgsStyleV2().defaultStyle()
defaultColorRampNames = myStyle.colorRampNames()
ramp = myStyle.colorRamp(defaultColorRampNames[8])

myRenderer.updateColorRamp(ramp)
layer.setRendererV2(myRenderer)
if iface.mapCanvas().isCachingEnabled():
    layer.setCacheImage(None)
else:
    iface.mapCanvas().refresh()
layer.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.