6

Is there a way to add labels of the added layers using python. I've tried these lines of code but no label shows after execution in QGIS 3.0

for layer in QgsProject.instance().mapLayers().values():
    layer.setCustomProperty("labeling/fieldName", "Id" )
    layer.setCustomProperty("labeling/placement", QgsPalLayerSettings.Horizontal)
    layer.setCustomProperty("labeling/predefinedPointPosition", QgsPalLayerSettings.BottomRight)
    layer.setCustomProperty("labeling/fontSize","10" )
    layer.setCustomProperty("labeling/bufferDraw", True)
    layer.setCustomProperty("labeling/enabled","true" )
    layer.triggerRepaint()

1 Answer 1

12

After surfing the platform. Found the following working solution;

for layer in QgsProject.instance().mapLayers().values():
    layer_settings  = QgsPalLayerSettings()
    text_format = QgsTextFormat()

    text_format.setFont(QFont("Arial", 12))
    text_format.setSize(12)

    buffer_settings = QgsTextBufferSettings()
    buffer_settings.setEnabled(True)
    buffer_settings.setSize(0.10)
    buffer_settings.setColor(QColor("black"))

    text_format.setBuffer(buffer_settings)
    layer_settings.setFormat(text_format)

    layer_settings.fieldName = "Id"
    layer_settings.placement = 4

    layer_settings.enabled = True

    layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
    layer.setLabelsEnabled(True)
    layer.setLabeling(layer_settings)
    layer.triggerRepaint()

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.