6

I'm trying to display labels using PyQGIS.

In this case, I create the layers manually, so I guess you need to add a "Label" attribute to the feature as well.

Therefore, I've written a little code whereof I think "should" work by following @Kezah's answer for QGIS 3.0: Question

The QGIS version I'm using is QGIS 3.22.

The problem is that no label is being shown.

Does perhaps somebody know a basic example of how to approach this correctly?

import sys
from qgis.gui import *
from qgis.core import *
from qgis.PyQt.QtWidgets import QMainWindow, QApplication
from qgis.PyQt.Qt import QVariant

class TestClass(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)

        self.canvas = QgsMapCanvas()
        self.project = QgsProject.instance()
        self.setCentralWidget(self.canvas)
        self.toolPan = QgsMapToolPan(self.canvas)

        self.pointl = QgsVectorLayer("Polygon?crs=epsg:4326", "poly", "memory")
        self.pointl.startEditing()
        geom = QgsGeometry()
        geom = QgsGeometry.fromWkt("POLYGON ((4.3003272 51.3235323, 4.3003272 51.3235367, 4.3003415 51.3235456, 4.3003407 51.3235478, 4.3003637 51.3235627, 4.3003736 51.3235524, 4.3003709 51.3235438, 4.3003673 51.3235367, 4.3003644 51.3235313, 4.3003579 51.3235134, 4.3003272 51.3235323))")
        feat = QgsFeature()
        feat.setGeometry(geom)
        self.pointl.dataProvider().addFeature(feat)
        self.pointl.dataProvider().addAttributes([QgsField("label", QVariant.String)])
        self.pointl.updateFields()
        for feat in self.pointl.getFeatures():
            feat.setAttribute("label", "Test Label")
        label_settings = QgsPalLayerSettings()
        label_settings.drawLabels = True
        label_settings.fieldName = 'label'
        self.pointl.setLabelsEnabled(True)
        self.pointl.setLabeling(QgsVectorLayerSimpleLabeling(label_settings))
        self.pointl.commitChanges()
        
        self.project.addMapLayer(self.pointl)
        self.canvas.setLayers([self.pointl])
        self.canvas.setExtent(self.pointl.extent())
        self.pan()
    
    def pan(self):
        self.canvas.setMapTool(self.toolPan)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = TestClass()
    test.show()
    sys.exit(app.exec_())

1 Answer 1

10

There is no problem with @Kezah's answer. I've edited the script and it works. Please check it. Avoid using startEditing() and dataProvider().addFeatures() together. Use either one. If you construct a large dataset, using dataProvider().addFeatures() is usually faster.

import sys
from qgis.gui import *
from qgis.core import *
from qgis.PyQt.QtWidgets import QMainWindow, QApplication
from qgis.PyQt.Qt import QVariant


class TestClass(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.canvas = QgsMapCanvas()
        self.project = QgsProject.instance()
        self.setCentralWidget(self.canvas)
        self.toolPan = QgsMapToolPan(self.canvas)
        
        ###### Edited Area
        self.pointl = QgsVectorLayer("Polygon?crs=epsg:4326", "poly", "memory")
        self.pointl.dataProvider().addAttributes([QgsField("label", QVariant.String)])
        self.pointl.updateFields()

        geom = QgsGeometry()
        geom = QgsGeometry.fromWkt("POLYGON ((4.3003272 51.3235323, 4.3003272 51.3235367, 4.3003415 51.3235456, 4.3003407 51.3235478, 4.3003637 51.3235627, 4.3003736 51.3235524, 4.3003709 51.3235438, 4.3003673 51.3235367, 4.3003644 51.3235313, 4.3003579 51.3235134, 4.3003272 51.3235323))")

        feat = QgsFeature(self.pointl.fields())
        feat.setGeometry(geom)
        feat["label"] = "Test Label"
        self.pointl.dataProvider().addFeatures([feat])
        ######

        label_settings = QgsPalLayerSettings()
        label_settings.drawLabels = True
        label_settings.fieldName = 'label'
        self.pointl.setLabelsEnabled(True)
        self.pointl.setLabeling(
            QgsVectorLayerSimpleLabeling(label_settings))

        self.project.addMapLayer(self.pointl)
        self.canvas.setLayers([self.pointl])
        self.canvas.setExtent(self.pointl.extent())
        self.pan()

    def pan(self):
        self.canvas.setMapTool(self.toolPan)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = TestClass()
    test.show()
    sys.exit(app.exec_())

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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