17

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.

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
user2956607
  • 171
  • 1
  • 4

1 Answers1

26

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

Assuming your layer has a color field (type: string), select (or activate) the layer in the QGIS ToC, open the QGIS Python console, and copy this code snippet:

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

for cat in layer.renderer().categories(): expr = """ + attr + ""='" + unicode(cat.value()) + "'"

for f in layer.getFeatures(expr):
    attrMap = {fieldIndex : cat.symbol().color().name()}
    attrFeatMap[f.id()] = attrMap

layer.dataProvider().changeAttributeValues( attrFeatMap )

After running it, you'll obtain this:

enter image description here

Let me know if you face any problem.

Germán Carrillo
  • 36,307
  • 5
  • 123
  • 178
  • Is there possibilite to do it for RGB? – Diogo Caribé Dec 04 '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 05 '15 at 02: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
  • 1
    @Paladini, just updated the answer to work with QGIS v3.x (tested on QGIS 3.16). – Germán Carrillo Oct 06 '21 at 04:09
  • v.3.26. Not work :( – Rudzik Aug 08 '22 at 16:24
  • Could neither get it to work under 3.26.3. Had to adjust the indents, so the code runs, but it doesn't write anything to the attribute table. To me, as a Python-noob, it seems like attrFeatMap is not populated... the last two lines are like layer.dataProvider().changeAttributeValues( attrFeatMap ) True attrFeatMap {} – Beni Dec 16 '22 at 11:08