5

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)

2 Answers 2

3

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

2
  • 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? Commented Jul 13, 2018 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
    Commented Jul 13, 2018 at 14:20
3

as I do not have enough reputation, yet, to add a comment to the answer from Joseph, I have to add a new one. As far as I understood, the intended use of QgsPropertyCollection.setProperty() is to use an enumeration value casted to integer (see the setProperty documentation).

Therefore, I think the ultimate solution in this case would be something like:

pc.setProperty(QgsPalLayerSettings.Color, prop)

The list of available entries for the QgsPalLayerSettings is given in the QgsPalLayerSettings.Property enum here.

I hope this helps.

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.