Sunday, 30 October 2016

Labeling line features using PyQGIS?


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()

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


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...