8

I wrote the following code in order to draw the line labels with multiple fields. However, the label do not appear automatically in QGIS and I have to switch the "Layer Properties/Labels", and toggle OK.

def labelLine(lyr, champNom1, champNom2):
    label = QgsPalLayerSettings()
    label.readFromLayer(lyr)
    label.enabled = True
    label.fieldName = '''concat('BASE: ' + to_string("''' + champNom1 + '''"),'\nL = ' + to_string("''' + champNom2 + '''") + 'm')'''
    label.placement= QgsPalLayerSettings.Line
    label.bufferDraw= True
    label.bufferSize= 1
    label.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'8','')
    label.writeToLayer(lyr)

def saveCoucheFRAC(): layer = iface.activeLayer() nom = nom2 + "_FRAC" lien = path2 + "_FRAC" + ".shp" QgsVectorFileWriter.writeAsVectorFormat(layer, lien, "utf-8", QgsCoordinateReferenceSystem(22332, QgsCoordinateReferenceSystem.EpsgCrsId), "ESRI Shapefile") #Charger cette couche dans QGis vlayer = QgsVectorLayer(lien, nom, "ogr") if not vlayer.isValid(): print " Verifier la validite du fichier" else: # appliquer les couleurs selon le niveau de tension avec la fonction appCouleur ci-dessous appCouleur(vlayer) # changer l'epaisseur de la couche ligne epaiLyr(vlayer, "0.7") # ajouter l'etiquette de longueur sur chaque segment labelLine(vlayer, "BASE", "Longueur_m") # Definir la visibilite de la couche entre ech min 0 et max 100 000 visLyr(vlayer, 0, 100000) #Charger dans le Canvas QgsMapLayerRegistry.instance().addMapLayer(vlayer) saveCoucheFRAC()

I try to add the following to enable the label draw but it does not work:

layer.triggerRepaint()

or

layer.commitChanges()
layer.updateExtents()

A screenshot of the map (After toggling OK, line labels appears in QGIS)

After toggling OK, line labels appears in QGIS

Taras
  • 32,823
  • 4
  • 66
  • 137
ennine
  • 863
  • 2
  • 10
  • 20

2 Answers2

1

It seems you need to define the placement for line geometries.

label.placement = QgsPalLayerSettings.Line
Matt
  • 16,843
  • 3
  • 21
  • 52
-1

You should add this statement: settings.isExpression = True. This can be used to display multiple labels!

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389