4

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)
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
ennine
  • 863
  • 2
  • 10
  • 20
  • 1
    Maybe try replacing \\ n with \n? So label.fieldName = "concat('BASE:', fieldName1, '\n', 'L =', fieldName2, 'm')". – Joseph Oct 17 '17 at 11:07
  • Thank you, I tried your proposal but it did not work. – ennine Oct 17 '17 at 12:50
  • What happens when you use it? Is it still on a single line? Is there an error in the expression? Maybe you can post a screenshot of how the label looks? – Joseph Oct 17 '17 at 13:30
  • With one field, it works very well:
  • label.fieldName = champNom1 The label, in this case it is the length of each segment of an electric line, appears correctly.

    • With the concat expression, there is no error after the code compilation but there is no label on the line segments.
    – ennine Oct 17 '17 at 18:39
  • This question is a duplicate of https://gis.stackexchange.com/questions/132905/multiline-field-name-label-referencing – YoLecomte Oct 17 '17 at 20:53