Skip to content

Instantly share code, notes, and snippets.

@Korto19
Last active April 23, 2021 15:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Korto19/18baf0c687bbac1bd37a726eb155e1fd to your computer and use it in GitHub Desktop.
Save Korto19/18baf0c687bbac1bd37a726eb155e1fd to your computer and use it in GitHub Desktop.
A QGIS field calculator expression to get the color of a categorized item
from qgis.gui import *
from qgis.utils import iface
@qgsfunction(args='auto', group='Custom')
def get_catg_color(value, feature, parent):
"""
Restituisce il colore RGBA dell'elemento categorizzato:
il campo in input e' quello utilizzato per la categorizzazione
Per i campi della categorizzazione numerici formattatarli opportunamente e
utilizzare la stessa espressione per catturarne il colore
Returns the RGBA color of the categorized element:
the input field is the one used for categorization
For numeric categorization fields, format them appropriately and
use the same expression to get its color
<h2>Example usage:</h2>
<ul>
<li>get_color("Area") -> '228,52,199,255'</li>
<li>get_color(to_string(format_number("Area",2))) -> '228,52,199,255'</li>
</ul>
"""
layer = iface.activeLayer()
renderer = layer.renderer()
if layer.renderer().type() == "categorizedSymbol":
campo = renderer.legendClassificationAttribute()
for cat in renderer.categories():
if str(value) == cat.value():
colorato = cat.symbol().symbolLayer(0).properties()['color']
break
return colorato
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment