2

I try to export all QGIS-LayerTreeGroups and LayerTreeLayer-definitions (as *.qlr) using following python code (recursive search to search the whole layerTree; the path to save the *.qlr is build from group- and layer-names).

I do not know how to use the "exportLayerDefinition(..,..)". Python says "[...] AttributeError: 'QgsLayerTreeLayer' object has no attribute 'exportLayerDefinition'" (line 8 +13)

(Using QGIS 2.14 / 2.16) My Code Sample is

def deeperExport(laTrGr, treeName):
    pos = 0
    for child in laTrGr.children():
        if isinstance(child, QgsLayerTreeGroup):
            treeName += "/" + child.name()
            deeperExport(child,treeName) 
            path= treeName + ".qlr"
            child.exportLayerDefinition(path, child.children())
            pos = treeName.rfind("/")
            treeName = treeName[0:pos]
        elif isinstance(child, QgsLayerTreeLayer):
            path = treeName+"/" + child.layerName()+".qlr"
            child.exportLayerDefinition(path, child.children())

#main 
root = QgsProject.instance().layerTreeRoot()
print root
treeName = "c:/..."
deeperExport(root, treeName)
1
  • 1
    From the doc, exportLayerDefinition is a static member of QgsLayerDefinition, meaning that you are supposed to call it that way: QgsLayerDefinition.exportLayerDefinition(...). – ArMoraer Aug 12 '16 at 13:48
2

With using the comment of ArMoraer I changed the code as described below - a addidion of missind directories is added to save the whole layer tree as like the qgis-project.

import os


def deeperExport(laTrGr, treeName):
    pos = 0
    for child in laTrGr.children():
        if isinstance(child, QgsLayerTreeGroup):
            treeName +="/" + child.name()
            deeperExport(child,treeName) 
            path= treeName + ".qlr"
            if not os.path.exists(treeName):
                os.makedirs(treeName)
            QgsLayerDefinition.exportLayerDefinition(path, child.children()) 
            print path
            pos = treeName.rfind("/")
            treeName = treeName[0:pos]
        elif isinstance(child, QgsLayerTreeLayer):
            path = treeName+"/" + child.layerName()+".qlr"
            print path
            QgsLayerDefinition.exportLayerDefinition(path, child.children()) 

#main 
root = QgsProject.instance().layerTreeRoot()
print root
treeName = 'C:/....'
deeperExport(root, treeName)
1
  • Very useful. You can except your own answer as the final answer to your question. Just click the hook to the left of your answer! – Stefan Feb 28 '18 at 12:39

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.