TransWikia.com

Multi-field labeling of shapefile with PyQGIS?

Geographic Information Systems Asked by ennine on December 2, 2020

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

One Answer

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

label.placement = QgsPalLayerSettings.Line

Answered by Matt Needle on December 2, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP