2

I would like my plugin to apply a QML style to an output layer. This consists of three parts:

  1. Packaging the QML file into the plugin.
  2. Referring to the QML file using a relative path.
  3. Setting the style on the output layer.

For number 1, I have saved my style as default.qml in a /styles/ subdirectory of the plugin, and I have added it like so into the resources.qrc file.

<RCC>
  <qresource prefix="/plugins/phylo_tree" >
     <file>styles/default.qml</file>
  </qresource>
</RCC>

I have then used resources.qrc to generate resources.py with pyrcc5

For number 2 - referring to the QML file by a relative path - my understanding is that the path should be :plugins/phylo_tree/styles/default.qml, as mentioned in this answer.

For number 3 - I have used the code in this answer to add a style to the output layer, using the postProcessAlgorithm function. This works if I use an absolute path to the QML file, but not when I use the relative path :plugins/phylo_tree/styles/default.qml: When using the relative path, the operation completes without any error message, but no style is applied.

TimD
  • 429
  • 3
  • 10

1 Answers1

1

You can apply style from .qml file to layer using this code:

import os
style_path = os.path.join(os.path.dirname(__file__), 'styles/default.qml')
layer.loadNamedStyle(style_path)

You first import os. Next get path to QML file by joining it`s relative path with plugin directory path. In the end apply style to layer.

PPZ
  • 46
  • 2
  • This is a completely different approach to the method I was trying to do, but it works! Thank you. – TimD Jun 07 '20 at 23:02