I'm trying to apply a color ramp on a categorized render in QGIS 3.4 (via the Python console).
I started by adapting the solution for a catagorized symbol layer - to QGIS 3.4 but this applies a random color scheme. Since then i searched for how to apply a color ramp, which i have started to adapt from an earlier solution for applying a color ramp.
So far I've got his:
# Get the active layer (must be a vector layer)
layer = QgsProject.instance().mapLayersByName("t_zpbo")[0]
# provide file name index and field's unique values
field = layer.fields().lookupField('zp_capamax')
unique_values = layer.uniqueValues(field)
## get default style
myStyle = QgsStyle().defaultStyle()
## get a list of default color ramps [u'Blues', u'BrBG', u'BuGn'....]
defaultColorRampNames = myStyle.colorRampNames()
## setting ramp to Reds, sixth index of defaultColorRampNames
ramp = myStyle.colorRamp(defaultColorRampNames[9])
# set up an empty categorized renderer and assign the color ramp
renderer = QgsCategorizedSymbolRenderer('zp_capamax', [])
renderer.setSourceColorRamp(ramp)
layer.setRenderer(renderer)
Unfortunately this returns the follwoing error:
TypeError: QgsCategorizedSymbolRenderer(attrName: str = '', categories: Iterable[QgsRendererCategory] = []): argument 1 has unexpected type 'int'
Which leaves me a little confused... as far as I can tell it doesn't seem to like the fact the values in my field are integers...
EDIT: I modified the original code i posted above to take into account the comments of Ben W (see below) - the code above doesnt return any error codes - but it doesn't seem to creates classes. When I look at the layer properties after I run the script I can see the styling is catagorized, and the right field is selected, and a color ramp is selected - but no classes appear.
field
which you are passing to the renderer constructor is an integer (since it returns the field index) but the constructor expects a string argument. Try passing your field name 'zp_capamax' instead.layer
in 2nd line andvl
in last line). Make them the same. Surprising you didn't get a name error?triggerRepaint
on your layer at the end. But bear in mind that doingsetSourceColorRamp
doesn't work like you hope it would! Yes, it changes the colour ramp in the symbology dialog, but it doesn't apply that ramp to the categories you create programmatically. For custom colours, you really have to create a colour and symbol and pass it to each category as you create it.