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

5
  • Could you paste a screenshot or an example of what is should be doing ? Is this question a duplicate of this one ? gis.stackexchange.com/questions/258753/…
    – gisnside
    Oct 23, 2017 at 15:29
  • Can you try : self.iface.mapCanvas().refreshAllLayers()
    – sigeal
    Oct 31, 2017 at 18:52
  • Unfortunatly, it did not work too
    – ennine
    Oct 31, 2017 at 20:53
  • can you add which version of qgis you are using?
    – LaughU
    Nov 16, 2017 at 8:25
  • I am using the latest version QGis2.18.14
    – ennine
    Nov 17, 2017 at 13:58

2 Answers 2

0

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

label.placement = QgsPalLayerSettings.Line
-1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.