3

How do I read and set label style settings in QGIS 3.0.

For instance, in QGIS 2.18 i had done:

props = {
    "labeling": "pal",
    "labeling/enabled": "true",
    "labeling/fontFamily": "Arial",
    "labeling/fontSize": "12",
    "labeling/fieldName": "Name",
    "labeling/bufferDraw": True,
    "labeling/bufferSize": "1",
    "labeling/bufferColor": "white"
    }
for k, v in props.items():
    my_layer.setCustomProperty(k, v)

How do I do the equivalent in QGIS 3.0?

7

I found the answer for QGIS 3.0:

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(1)
buffer_settings.setColor(QColor("white"))

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

layer_settings.fieldName = "my_attribute"
layer_settings.placement = 2

layer_settings.enabled = True

layer_settings = QgsVectorLayerSimpleLabeling(layer_settings)
my_layer.setLabelsEnabled(True)
my_layer.setLabeling(layer_settings)
my_layer.triggerRepaint()
  • any chance you can share where this is specified? console? .ini file? – Kapanther Mar 21 '18 at 13:22
  • I was using this code inside a Plugin. I needed to create a memory layer, populate it and set the label style. – Kezah Mar 22 '18 at 23:24
  • Note: there is no enabled attribute for QgsPalLayerSettings, meaning that the layer_settings.enabled = True line doesn't do anything and can/should be removed. – Jonny Oct 18 '18 at 14:17
  • Is this the definite answer? The QGIS3 solution is much more complicated and much less elegant, than the QGIS2 solution. Complex stiles have often more than 20 characteristics. – AndreasK Nov 8 '18 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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