Monday, 4 May 2015

qgis - Load .qlr with loadNamedStyle


I tried


>>>QgsVectorLayer.loadNamedStyle(r'C:\Some\Path\FOO.qlr')

Get this error:



Traceback (most recent call last):
File "", line 1, in
TypeError: arguments did not match any overloaded call:
QgsVectorLayer.loadNamedStyle(QString, bool) -> (QString, bool): first argument of unbound method must have type 'QgsVectorLayer'
QgsVectorLayer.loadNamedStyle(QString) -> (QString, bool): first argument of unbound method must have type 'QgsVectorLayer'

Then i tried:


>>>vlayer = QgsVectorLayer
>>>vlayer = loadNamedStyle(r'C:\Some\Path\FOO.qlr')


and gets the same error. The question is simple. How do i load a .qlr-file from path?


My research: The developers archive, The C++ documentation (which i suppose is good but I don't know C++), Some one with a similar problem


I have a hard time finding Api for the py qgis.



Answer



QGIS 2.x


The source file for layer definitions indicates that you need to use loadLayerDefinition and not loadNamedStyle. Therefore we need to specify a string path and a QgsLayerTreeGroup in which the layer will be loaded into. Then we can either:




  • Create a new empty group in the Table of Contents:


    root = QgsProject.instance().layerTreeRoot()

    group = root.addGroup("group1")
    QgsLayerDefinition().loadLayerDefinition('C:/Some/Path/FOO.qlr', group)


  • Or use an existing group:


    root = QgsProject.instance().layerTreeRoot()
    group = root.findGroup('group1')
    QgsLayerDefinition().loadLayerDefinition('C:/Some/Path/FOO.qlr', group)





QGIS 3.x


The QgsLayerDefinition().loadLayerDefinition() function now requires the project instance as an input parameter. So the last line of each of the above code snippets can be replaced from:


QgsLayerDefinition().loadLayerDefinition('C:/Some/Path/FOO.qlr', group)

to:


QgsLayerDefinition().loadLayerDefinition('C:/Some/Path/FOO.qlr', QgsProject.instance(), group)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...