TransWikia.com

QGIS Python API set label color based on attribute field

Geographic Information Systems Asked by Zekun on May 20, 2021

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

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

Correct answer by Kadir Şahbaz on May 20, 2021

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.

Answered by ahmadhanb on May 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP