Wednesday, 3 January 2018

Multi-line labeling of a shapefile layer with pyQGis


I want to label a shp layer on two lines with pyQGis. I managed to do it with only one field, but with two or more fields (using concat) it does not work anymore.


Here is the code I wrote:


def labelLine (lyr, fieldNom1, fieldNom2):
# This function shows the labels of 2 fields "fieldName1" and "fieldName2" for a Line layer lyr
label = QgsPalLayerSettings ()
label.readFromLayer (lyr)
label.enabled = True

# we concatenate the two fields
label.fieldName = "concat ('BASE:', fieldName1, '\\ n', 'L =', fieldName2, 'm')"
label.placement = QgsPalLayerSettings.Line
label.bufferDraw = True
label.bufferSize = 1
label.setDataDefinedProperty (QgsPalLayerSettings.S ize, True, True, '8', '')
label.writeToLayer (lyr)

Answer



Perhaps try something like the following expression. We can use the to_string function from the Field Calculator to convert any value from a field to a string (as you can't concatenate strings and values):


'''concat('BASE: ' + to_string("''' + fieldName1 + '''"),'\nL = ' + to_string("''' + fieldName2 + '''") + 'm')'''




So your code could look like:


def labelLine(lyr, fieldName1, fieldName2):
label = QgsPalLayerSettings()
label.readFromLayer(lyr)
label.enabled = True
label.fieldName = '''concat('BASE: ' + to_string("''' + fieldName1 + '''"),'\nL = ' + to_string("''' + fieldName2 + '''") + 'm')'''
label.placement = QgsPalLayerSettings.Line
label.bufferDraw = True

label.bufferSize = 1
label.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '8', '')
label.writeToLayer(lyr)
lyr.setCustomProperty("labeling/drawLabels", True)
lyr.triggerRepaint()

lyr = iface.activeLayer()
labelLine(lyr, 'fieldName1', 'fieldName2')

Example:



Example


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