19

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

28
+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.

9
  • Is there possibilite to do it for RGB? Commented 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()) Commented Dec 5, 2015 at 2:38
  • 1
    Still valid in qgis 3.6, apart from the API rename rendererV2 -> renderer
    – sabas
    Commented 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
    Commented Jul 29, 2019 at 13:59
  • 1
    @Paladini, just updated the answer to work with QGIS v3.x (tested on QGIS 3.16). Commented Oct 6, 2021 at 4:09

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.