1

I am currently working on a project in which I need to turn on the "RESULT_PRE" field label so this is the code but the field holds decimal values and I want to give a precision of 3 digits. How can I do that?

from qgis.core import QgsProject
from qgis.core import *
from qgis.utils import iface
from qgis.core import QgsEditorWidgetSetup,QgsField
from qgis.core import QgsPalLayerSettings, QgsTextFormat


# Get the active layer
layer = iface.activeLayer()
layer.setLabelsEnabled(True)
label_Settings = QgsPalLayerSettings()
label_Settings.fieldName = "RESULT_PRE"

# Optional: Set label formatting (e.g., font, size, color)
text_format = QgsTextFormat()
text_format.setFont(QFont("Arial", 12))  # Set font and size
label_Settings.setFormat(text_format)

# Enable labelling for the layer
layer.setLabeling(QgsVectorLayerSimpleLabeling(label_Settings))

# Refresh the layer to apply the changes
layer.triggerRepaint()
0

1 Answer 1

0

You are almost there, there are only two additional settings parameters that you were missing label_Settings.formatNumbers = True and label_Settings.decimals = 3 of the QgsPalLayerSettings class.

So, in the end, your code may look like this:

from qgis.core import QgsProject
from qgis.core import *
from qgis.utils import iface
from qgis.core import QgsEditorWidgetSetup,QgsField
from qgis.core import QgsPalLayerSettings, QgsTextFormat
    

# Get the active layer
layer = iface.activeLayer()
layer.setLabelsEnabled(True)
label_Settings = QgsPalLayerSettings()
label_Settings.fieldName = "RESULT_PRE"
label_Settings.formatNumbers = True # active to fix number of decimal places
label_Settings.decimals = 3 # set up required precision

# Optional: Set label formatting (e.g., font, size, color)
text_format = QgsTextFormat()
text_format.setFont(QFont("Arial", 12))  # Set font and size
label_Settings.setFormat(text_format)

# Enable labeling for the layer
layer.setLabeling(QgsVectorLayerSimpleLabeling(label_Settings))

# Refresh the layer to apply changes
layer.triggerRepaint()

References:

0

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.