3

suppose I have a shapefile that have an attribute, and I want that attribute to be shown with white background behind the text in the viewport.

This is what I want to accomplish:

labels with white background

I've searched the internet and tried this: https://gis.stackexchange.com/a/277111/51131 but it only shows the labels without the background.

1 Answer 1

5

Only a slight adjustment was required to the code posted already (on https://gis.stackexchange.com/a/277111/51131):

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

    background_color.setFillColor(QColor('white'))
    background_color.setEnabled(True)

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

    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 = "Label"
    layer_settings.placement = 4

    layer_settings.enabled = True

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

Make sure to upgrade to the newest QGIS version (3.2). Instantiating the QgsTextBackgroundSettings class does not seem to function properly in 3.0.

4
  • Thank you, it's working. Where do you learn this from?
    – Ayato
    Commented Jul 2, 2018 at 13:29
  • You welcome! Essentially I had a look at the QGIS Python API, and what is the way to set a background to the QgsTextFormat object. Have a look here: qgis.org/pyqgis/master/core/Text/…
    – 15Step
    Commented Jul 2, 2018 at 14:28
  • How did you know if it had to be set enabled to True? How to use RGB color code instead of color's name?
    – Ayato
    Commented Jul 2, 2018 at 22:15
  • Under the method 'enabled' for the QgsTextBackgroundSettings, it says: enabled(self) → bool. To use RGB, simply pass RGB arguments instead of the name to the QColor class. Example: QColor(0,255,0) for green.
    – 15Step
    Commented Jul 3, 2018 at 8:44

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.