Monday 26 October 2015

labeling - Setting a Background Color with RVBT field with python


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())

Answer



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


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...