[GIS] Labeling line features using PyQGIS

labelingpyqgisroad

I used the following code to label the line features(roads) in a layer.It works in the console, but not by python code(application) It works for the points too.

What did I do wrong?

 def labell(self):
    layer = self.iface.mapCanvas().currentLayer()
    palyrr = QgsPalLayerSettings()
    palyrr.readFromLayer(layer)
    palyrr.enabled = True
    palyrr.fieldName = 'name'
    palyrr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'08','')
    palyrr.writeToLayer(layer)
    layer.commitChanges()
    self.iface.mapCanvas().refresh()

Best Answer

I don't know what could be the difference between console and plugin, I think it should to work either way. Also you try to replace layer.commitChanges() (which makes not sense there) with layer.triggerRepaint() and look if that helps (note it is not necessary to call mapCanvas.refresh()). You can also use custom properties for the layer to enable labeling, a sample code is the following:

layer = iface.activeLayer()
layer.setCustomProperty("labeling/fieldName", "name" )
layer.setCustomProperty("labeling/placement", QgsPalLayerSettings.Line)
layer.setCustomProperty("labeling/fontSize","8" )
layer.setCustomProperty("labeling/enabled","true" )
layer.triggerRepaint()

EDIT

for linear features you have to set the placement property as well. I changed the above code. Your first posted code should also work by adding the following line:

palyrr.placement = QgsPalLayerSettings.Line

You can use other placement attributes please have a look at this link