[GIS] How to copy the color styling to a color column in a layer’s attribute table

leafletpyqgisqgisstyle

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.

Best Answer

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.

Related Question