Thursday 22 March 2018

Multi-field labeling of shapefile with PyQGIS?


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




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