PyQGIS – Failure to Display Label Styles from QML Style File for Vector Layer

linepyqgisqmlstyle

The following PyQGIS doesn't seem to work to load my label style (from a QML style file) for a vector layer created from WKT LINESTRINGs. The vector layer does display but not the line label styles.

After running the script, I would expect the labels to be displayed in QGIS but they are not. Maybe I am wrong but I would expect the layer labels to be set to "Single Labels" Here is the script for QGIS 3.28.1:

uriLines = 'file:///Users/Current%20Work/test%20lines.txt?type=csv&delimiter=;%7C&quote=&escape=&maxFields=10000&detectTypes=yes&wktField=Geom&crs=EPSG:4326&spatialIndex=no&subsetIndex=no&watchFile=no'
vLinesLayer = QgsVectorLayer(uriLines, 'Lines', 'delimitedtext')

if not vLinesLayer.isValid():
   print("Lines layer not loaded")

vLinesLayer.loadNamedStyle('/Users/Current\ Work/test\ style.qml')
QgsProject.instance().addMapLayer(vLinesLayer)
vLinesLayer.triggerRepaint()

Best Answer

You do not need to escape the space character with a backslash in the quoted string defining your filename.

Use this instead:

uriLines = 'file:///Users/Current%20Work/test%20lines.txt?type=csv&delimiter=;%7C&quote=&escape=&maxFields=10000&detectTypes=yes&wktField=Geom&crs=EPSG:4326&spatialIndex=no&subsetIndex=no&watchFile=no'
vLinesLayer = QgsVectorLayer(uriLines, 'Lines', 'delimitedtext')

if not vLinesLayer.isValid():
   print ("Lines layer not loaded")

vLinesLayer.loadNamedStyle(r'/Users/Current Work/test style.qml')
QgsProject.instance().addMapLayer(vLinesLayer)
vLinesLayer.triggerRepaint()

But prefer using file names without any special characters, such a spaces, in their full path.

Also make sure your .qml file is correctly formatted.