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?

Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
spencerrecneps
  • 1,888
  • 1
  • 17
  • 22

2 Answers2

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]"
dmh126
  • 6,732
  • 2
  • 21
  • 36
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)
maz
  • 173
  • 1
  • 7