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.
The attribute table looks like this:
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.
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), ' ', ',')")
Correct answer by Kadir Şahbaz on May 20, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP