16

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.

0

1 Answer 1

24
+25

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.

6
  • Is there possibilite to do it for RGB? Dec 4, 2015 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()) Dec 5, 2015 at 2:38
  • 1
    Still valid in qgis 3.6, apart from the API rename rendererV2 -> renderer
    – sabas
    Mar 28, 2019 at 21:33
  • Didn't worked on QGis 3.6 here. I've renamed rendererV2 to renderer, but didn't worked.
    – Paladini
    Jul 29, 2019 at 13:59
  • @Paladini, just updated the answer to work with QGIS v3.x (tested on QGIS 3.16). Oct 6, 2021 at 4:09

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.