2

I'm trying to label a shapefile with coordinates from attribute table with pyqgis.

I've been messing around with labeling shapefiles with python, I can do most things that I need, but the main setting still eludes me. How do I set data defined coordinates with python from attribute table (label_x, label_y).

Below is just a sample code for triggering labels but it does not have anything in it to trigger labels from coordinates.

myLayer = QgsProject.instance().mapLayersByName('test_poligon')[0]    
settings  = QgsPalLayerSettings()
settings.fieldName = "Fid"
settings.placement = 3
settings.enabled = True
settings = QgsVectorLayerSimpleLabeling(settings)
myLayer.setLabelsEnabled(True)
myLayer.setLabeling(settings)
myLayer.triggerRepaint()
1
  • Hi @anjisa, try settings.Positionx = "Lon" settings.Positiony= "Lat" if your coordinates are in fields called Lat and Long
    – ian
    Aug 23 '19 at 7:52
2

You need to use the QgsProperty() and QgsPropertyCollection() classes to set the data defined properties. The enum property value 9 and 10 are for the X and Y positions respectively which are listed (here under "Property"):

myLayer = QgsProject.instance().mapLayersByName('test_poligon')[0]

#Create Property Collection
pc = QgsPropertyCollection('qpc')

#Set data-defined properties for X-position
x_prop = QgsProperty()
x_prop.setField("label_x")
pc.setProperty(9, x_prop)

#Set data-defined properties for Y-position
y_prop = QgsProperty()
y_prop.setField("label_y")
pc.setProperty(10, y_prop)

#Apply settings
settings = QgsPalLayerSettings()
settings.setDataDefinedProperties(pc)
settings.enabled = True
settings.fieldName = "Fid"
settings.placement = 3
settings = QgsVectorLayerSimpleLabeling(settings)
myLayer.setLabelsEnabled(True)
myLayer.setLabeling(settings)
myLayer.triggerRepaint()
2
  • 1
    This worked perfectly and is very elegant, thank you very much! :)
    – anjisa
    Aug 25 '19 at 13:03
  • @anjisa - Most welcome, glad it helped :)
    – Joseph
    Aug 26 '19 at 9:07

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.