2

I am trying to set a layer's style using pyQGIS. My primary idea was to set the style from a string, but unfortunately I can only do it from a file. This code works as a charm:

        filename= QDir.tempPath() + "/style.sld"
        f = open(filename,'w')

        if os.path.exists(filename):

            f.write(style)
            f.close()
            ret=layer.loadSldStyle(filename)

            if ret:
                self.log(logging.DEBUG, "Style loaded")
            else:
                self.log(logging.DEBUG, "Style not loaded: " + errorMsg)

            os.remove(filename)

As you can see, I am writing the style string into a temporary file, loading the style and then removing it. What I would like to do instead, is to pass the string straight to the readSld function, which is wrapped in loadSldStyle:

        d = QDomDocument()
        ret=d.setContent(style)

        if ret:
            self.log(logging.DEBUG, "Document created")
        else:
            self.log(logging.DEBUG, "Document not created")

        self.log(logging.DEBUG, "content: " + d.toString())

        myRoot=d.firstChildElement
         ("StyledLayerDescriptor")

        if myRoot is None:
            self.log(logging.ERROR,  u"Could not get "
                "root element")
            return

        namedLayerElem=myRoot.firstChildElement
         ("namedLayerElem")

        if namedLayerElem is None:
            self.log(logging.ERROR,  u"Could not find "
                "NamedLayer")
            return

        errorMsg = str("")
        ret=layer.readSld(namedLayerElem,errorMsg)

Please note that this is very similar to the C++ code for the method loadSldStyle on the QgsMapLayer class implementation

The QDomDocument contains the correct style, and the myRoot and namedLayerElem nodes are correctly created. Nevertheless, readSld returns false, and worst of all, the error string is empty so I have no idea what is going on! Any advice on what might be the problem? I know that this function has been ported to sip.

1 Answer 1

1

The readSld has the function signature

    
virtual bool    readSld (const QDomNode &node, QString &errorMessage)

So I dont see why your code should not work, maybe you could try the passing the root ???


layer.readSld(myRoot)

1
  • According to the implementation on the C++ code, you need to pass the "NamedLayer" element, not the top element "StyledLayerDescriptor"
    – doublebyte
    Jan 10, 2017 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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