I have a polygon layer in QGIS that I have applied a random color style to each polygon. Under Layer Properties -> Style I selected a Categorized style and then generated a random color ramp. I added a color column to the layer table. Is there a way to automatically copy the color assigned in the style to the color column for each polygon in the form "#ff0000".

Ultimately, I want to export it as a GeoJSON layer and import it into a leaflet map. The color column will set the color in leaflet.


You could use PyQGIS for that (not sure is the best solution for it, though).

Select (or activate) the layer in the QGIS ToC, open the QGIS Python console, and copy this code snippet:

prefix = "'"
layer = iface.activeLayer()
attr = layer.rendererV2().classAttribute()
attrColor = 'color' # Name of the field to store colors
fieldIndex = layer.dataProvider().fieldNameIndex(attrColor)
attrFeatMap = {}

for cat in layer.rendererV2().categories(): 
  expr = "\""+attr+"\"="+prefix+unicode(cat.value())+prefix
  for f in layer.getFeatures(QgsFeatureRequest(QgsExpression(expr))):
    attrMap = { fieldIndex : cat.symbol().color().name()}
    attrFeatMap[ f.id() ] = attrMap

layer.dataProvider().changeAttributeValues( attrFeatMap )

I assume your field to store colors is called 'color'. After running it, I've obtained this:

enter image description here

Let me know if you face any problem.

  • Is there possibilite to do it for RGB? – Diogo Caribé Dec 4 '15 at 19:58
  • 1
    Sure. Instead of calling cat.symbol().color().name(), do something like this: str(cat.symbol().color().red()) +','+ str(cat.symbol().color().green()) +','+ str(cat.symbol().color().blue()) – Germán Carrillo Dec 5 '15 at 2:38
  • 1
    Still valid in qgis 3.6, apart from the API rename rendererV2 -> renderer – sabas Mar 28 '19 at 21:33
  • Didn't worked on QGis 3.6 here. I've renamed rendererV2 to renderer, but didn't worked. – Paladini Jul 29 '19 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.