Thursday 17 November 2016

qgis - How to label vector features programmatically?


I am using python for QGIS 2.0.1 and I have a vector layer of points representing the positions of state labels. I want to display the 'state abbreviation' attribute on the corresponding point for each feature.


Does anyone have an example using QgsPalLabeling to do this? Any other suggestions are also appreciated.


This is a fairly simple process using the new Labeling tab of the GUI, but I have not found any documentation to make this work programmatically using pyQGIS.



Answer



Just figured this one out thanks to a modification of an older post by dakcarto.


Basically the python would need to look like this (replace everything in bold):


palyr = QgsPalLayerSettings()
palyr.readFromLayer(My Vector Layer)
palyr.enabled = True

palyr.fieldName = 'My Attribute Field Name'
palyr.placement= QgsPalLayerSettings.OverPoint
palyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'8','')
palyr.writeToLayer(My Vector Layer)

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...