4

I am trying to find a way to export a layer in a QLR file in PyQGIS. I want to do the same as right-click and export to layer definition file.

I know that I have to use QgsLayerDefinition.exportLayerDefinition and it needs a QgsLayerTreeNode parameter. But I don't know the steps to take a QgsVectorLayer and put it in a QgsLayerTreeNode.

I also need to do the reverse, load a QLR file and show the layer in QGIS.

1 Answer 1

7

Export

First, select a layer or a group layer.

current_node = iface.layerTreeView().currentNode()
QgsLayerDefinition().exportLayerDefinition("c:/path/of/file.qlr", [current_node])

Import

Solution 1:

You can import .qlr file using loadLayerDefinitionLayers method. This method just needs the path of .qlr file, and returns a list of layers defined in it. Even if defined one layer.

layer_list = QgsLayerDefinition().loadLayerDefinitionLayers("c:/path/of/file.qlr")
QgsProject.instance().addMapLayers(layer_list)

Solution 2:

Or you can prefer using loadLayerDefinition method. In this case you need QgsProject reference and root/group node.

project = QgsProject.instance()
root = project.layerTreeRoot()

QgsLayerDefinition().loadLayerDefinition("c:/path/of/file.qlr", project, root) 
2
  • The solution 1 is working, thank you. I also need to do the reverse : export a layer to a QLR file.
    – Math
    Feb 20, 2020 at 16:14
  • 1
    Thank you for the export solution, it works. I guess that unless I keep the currentNode in a variable, the layer must be in the toc to do this? I mean, having a QgsVectorLayer variable is not enough? Since QgsVectorLayer probably doesn't have symbology information.
    – Math
    Feb 20, 2020 at 18:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.