In QGIS Expression builder. I want to obtain the color code of the current feature.

I mean:

My layer contains lines, each one is painted with a different color. Now I want to assign that color to its label. In label definition, in the color property's expressions builder, how could I obtain that attribute?

I tried:

attribute( $currentfeature, 'color')

But it is not working...

  • by the way I am using QGIS 2.8.2 – Egidi Jun 25 '15 at 12:36

In QGIS >= 2.14 you can use the symbol_color variable. Eg, set a data defined override for your label color to the expression @symbol_color


Can it be done. Of couse with QGIS the answer is normally yes.

Lets take our vector layer with some normal labels and symbols:

enter image description here

Now add a data defined color for the buffer:

enter image description here

Click on Edit and select the function editor.

enter image description here

Click new file and give it a name (called mine colorfuncs)

Paste the following code

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def symbol_color(layername, feature, parent):
    layer = QgsMapLayerRegistry.instance().mapLayersByName(layername)[0]
    r = layer.rendererV2()
    symbol = r.symbolForFeature(feature)
    values = symbol.color().getRgb()
    return "{}, {}, {}, {}".format(*values)

Should look like this:

enter image description here

Hit Run Script

Jump back over to the expressions tab and use the new function:


We have to give it the name because expressions don't know about the layer only the feature.

Hit OK and Apply. BAM!

enter image description here

hmm almost. We just have to tweak the transparecny of the buffer:

enter image description here


enter image description here

  • Hi, @Nathan W very useful your script. What is 'Pits' in you example? – Egidi Jun 25 '15 at 13:41
  • The layer name of the layer you are styling. – Nathan W Jun 25 '15 at 13:44
  • mmm QGIS gets stuck when i type the last character of the layer. In my case symbol_color('itineraries'). When I type the last s QGIS crashes and closes... – Egidi Jun 25 '15 at 13:57

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.