6

I need to apply a .qml style to a layer on my map as part of a Python plugin. I gather that this can be done via QgsMapLayer.loadNamedStyle(). The problem I have is that my .qml file is stored within my plugin directory and I can't figure out how to reference the path at runtime.

The plugin is in my user plugin directory (/home/[user]/.qgis2/python/plugins/[plugindirectory]) not the main QGIS plugin directory, so I can't get a reference via qgsApplication.pluginPath().

What's the best way to accomplish this?

1
  • Would the answer for this post help where you set a fixed path to your .qml file?
    – Joseph
    Nov 12, 2015 at 13:16

2 Answers 2

8
import os

path = os.path.dirname(os.path.abspath(__file__))

Now path variable stores your path to the plugin directory which contains plugin.py:

>>> path
>>> "/home/[user]/.qgis2/python/plugins/[plugindirectory]"
8

The shortest way to get the path to your plugin directory:

import os

plugin_path = os.path.dirname(__file__)

So the path of your .qml file could be:

qml_path = plugin_path + "/myFile.qml"

Finally, you can load the .qml file to your QgsVectorLayer:

myLayer.loadNamedStyle(qml_path)

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.