8

I'm trying to set the text label color and size based on the attribute table. I got the size setting correctly but not the color.

My current result looks like this (The symbol has been set to be transparent), and I want to give different colors to different text labels.

enter image description here

The attribute table looks like this:

enter image description here

The code is as following:

vlayer = QgsProject.instance().mapLayersByName(layer_name)[0]
vlayer.renderer().symbol().setOpacity(0.0)

pc=QgsPropertyCollection('Text')
color_prop=QgsProperty()
color_prop.setField("color")

size_prop = QgsProperty()
size_prop.setField("size")
pc.setProperty(QgsPalLayerSettings.Color,color_prop)
pc.setProperty(QgsPalLayerSettings.Size,size_prop)

label_settings = QgsPalLayerSettings()
text_format = QgsTextFormat()

label_settings.setDataDefinedProperties(pc)

label_settings.fieldName = 'name'
label_settings.setFormat(text_format)

vlayer.setLabeling(QgsVectorLayerSimpleLabeling(label_settings))
vlayer.setLabelsEnabled(True)
vlayer.triggerRepaint()

I wonder where is wrong with the color setting in the code? My best guess is that the color field in the attribute table is not what QGIS requires, but I'm not sure what should be the correct format.

2 Answers 2

11

Replace spaces in color value to commas. 100 150 0 -> 100,150,0

Or change

color_prop.setField("color")

into

color_prop.setExpressionString("replace(trim(color), ' ', ',')")

enter image description here

0
7

You need to put comma separator between the RGB color in the color field in the attribute table, and the code will work perfectly:

enter image description here

I did not change anything in the code.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.