QGIS 3 – Setting Relative Path to SVG File in Plugin Folder for .SLD Files with PyQGIS

pyqgisqgisqgis-3sldsvg

I'm trying to update an old plugin to QGIS3 where we use default svg files (in the plugin folder) as markers. It is important that it is the plugin folder since I just to have the entire plugin in one location.

In QGIS2.18 I could specify the path to the svg marker as: :/PLUGIN_NAME/IMAGE_FOLDER/FILENAME.svg

Update:
I use an .sld file to specify the .svg path (and other attributes like name etc.) The
<se:OnlineResource xlink:type="simple" xlink:href=":/PLUGIN_NAME/IMAGE_FOLDER/FILENAME.svg"/>

When I try it now in QGIS3 I just gets ? instead of the svg symbol, unless I use absolute paths to the plugin and the image folder 🙁

Update:
I tried to add %AppData%/QGIS/QGIS3/profiles/default/python/plugins in front of PLUGIN_NAME, hence without success.

The .qgs file is used in multiple computers, so I want to specify a relative path in the .sld files to the svg file.

Any suggestions how to write it in QGIS3?

Best Answer

In QGIS2.18 I could specify the path to the svg marker as: :/PLUGIN_NAME/IMAGE_FOLDER/FILENAME.svg

Paths that start with :/ (and qrc:///) are paths to Qt resources. I assume there is a .qrc file which has been compiled/packaged to a resources.py file. The file from QGIS 2 is not compatible with QGIS 3 and you need to recreate the file to be able to continue to use resources (and therefore also paths that start with :/)

Alternatively you can also specify the full path to the svg file (as you post yourself as an answer).

This can also be automated, the following snippet can be used to determine the plugin path:

import os 
plugin_path = os.path.dirname(os.path.realpath(__file__)) # Potentially fix subdirectories

Then check if this path is already configured and add it if missing

svg_paths = QgsSettings().value('svg/searchPathsForSVG')
if plugin_path not in svg_paths:
    QgsSettings().setValue('svg/searchPathsForSVG', svg_paths + [plugin_path])
Related Question