4

I'm trying to set the color of a background of a layer. To do this i created an attribute "Color" with the RVBT numbers associate to each feature. As in the picture, i want to set the color with those features to set differents color, but i don't know how to do this with python.

Here is an image :

enter image description here

Here is my code (I set red color for example) :

background_color = QgsTextBackgroundSettings()
background_color.setFillColor(QColor('red'))
background_color.setEnabled(True)  
layer_settings  = QgsPalLayerSettings()
text_format = QgsTextFormat()
text_format.setFont(QFont("MS Shell Dlg 2"))
text_format.setSize(12.5)
text_format.setColor(QColor("black"))
text_format.setFont(QFont("MS Shell Dlg 2",11,QFont.Bold))
text_format.setBackground(background_color)
layer_settings.setFormat(text_format)
layer_settings.fieldName = "Valeur"
layer_settings.enabled = True
layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
layer.setLabelsEnabled(True)
layer.setLabeling(layer_settings)
layer.triggerRepaint()
qgis.utils.iface.layerTreeView().refreshLayerSymbology(layer.id())

1 Answer 1

4

You need to use the QgsProperty() and QgsPropertyCollection() classes to set the data defined properties. The enum property value 58 is for the background colour (see here for a list of data definable properties):

layer = iface.activeLayer()

background_color = QgsTextBackgroundSettings()
background_color.setEnabled(True)

# Set up the data-defined properties
prop = QgsProperty()
prop.setField("Couleur")
pc = QgsPropertyCollection('ShapeFillColor')
pc.setProperty(58, prop)
layer_settings = QgsPalLayerSettings()
layer_settings.setDataDefinedProperties(pc)

text_format = QgsTextFormat()
text_format.setFont(QFont("MS Shell Dlg 2"))
text_format.setSize(12.5)
text_format.setColor(QColor("black"))
text_format.setFont(QFont("MS Shell Dlg 2",11,QFont.Bold))
text_format.setBackground(background_color)
layer_settings.setFormat(text_format)
layer_settings.fieldName = "Valeur"
layer_settings.enabled = True
layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
layer.setLabelsEnabled(True)
layer.setLabeling(layer_settings)
layer.triggerRepaint()
iface.layerTreeView().refreshLayerSymbology(layer.id())

Result

9
  • 1
    Thank you very much ! Commented Jun 20, 2019 at 13:38
  • @ValentinL. - Most welcome! Glad it helped :)
    – Joseph
    Commented Jun 20, 2019 at 13:40
  • Do you know the enum property for "Fill Color" of a Simple Marker from Single symbol property ? Commented Jun 20, 2019 at 13:49
  • @ValentinL. - It's 3. It's supposed to be mentioned here but I guess they forgot to update it :)
    – Joseph
    Commented Jun 20, 2019 at 14:11
  • 1
    Thank you so much @Joseph. Commented Aug 1, 2019 at 10:44

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.