1

Set label font color using data defined property in PyQGIS 2 is well established, e.g. in another thread

However, PyQGIS 3 completely changed the way this works with no well documented examples. So, how to setup labels whose colors are based on data defined property. Here is my initial try, the label text show up, but the label's font color is not changing as i specified to be dependent upon the 'color' field values:

prop=QgsProperty()
prop.setField("Color")
pc=QgsPropertyCollection('mycol')
pc.setProperty(0,prop)
pal_layer=QgsPalLayerSettings()
pal_layer.setDataDefinedProperties(pc)
pal_layer.fieldName="value"
pal_layer.enabled=True
labeler=QgsVectorLayerSimpleLabeling(pal_layer)
layer.setLabeling(labeler)
layer.setLabelsEnabled(True)
0

You are setting the size property to take ownership of the field "Color" with this line:

pc.setProperty(0,prop)

The 0 key value is for size, 1 is for bold style etc. The value you want is 4:

pc.setProperty(4,prop)

This will set the colour property to take the field as its expression:

Label font colour

  • 1
    thanks, that worked. I would really hope the first int argument for setProperty to be an enumeration type, it's kinda hard to remember 0 is for size and 4 is for color etc, plus is there documentation on this on the web? – For Comment Jul 13 '18 at 14:13
  • @ForComment - Most welcome! Unfortunately, I could not find anything in terms of usage in any documentation or the QGIS API docs. I'm hoping these would be updated to reflect such properties :) – Joseph Jul 13 '18 at 14:20

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.