Wednesday, April 18, 2012

Native SLD support in QGIS

The current Quantum GIS master (i.e. the latest development version) supports now loading and saving of Styled Layer Descriptor (SLD) styles in the layer properties dialog.

The QGIS API has been extended by the new methods saveSldStyle and loadSldStyle in QgsMapLayer and writeSld and loadSld in QgsVectorLayer. Currently these methods are not yet available in the Python API, but it is simple to add them in the corresponding SIP files.

To write the current layer style to a file, type in the Python console:
l = qgis.utils.iface.activeLayer()
It's is also possible to get the current layer style as string:
# Get the active layer
l = qgis.utils.iface.activeLayer()

# Create a new XML document
document = QDomDocument()
header = document.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"" )
document.appendChild( header )
# Create the SLD root element
root = document.createElementNS( "", "StyledLayerDescriptor" )
root.setAttribute( "version", "1.1.0" )
root.setAttribute( "xsi:schemaLocation", "" )
root.setAttribute( "xmlns:ogc", "" )
root.setAttribute( "xmlns:se", "" )
root.setAttribute( "xmlns:xlink", "" )
root.setAttribute( "xmlns:xsi", "" )
document.appendChild( root )

# Create the NamedLayer element
namedLayerNode = document.createElement( "NamedLayer" )
root.appendChild( namedLayerNode )
errorMsg = QString("")
l.writeSld(namedLayerNode, document, errorMsg)

print document.toString( 4 )
It's still necessary to load SLD styles manually. SLD styles, unlike QGIS styles (.qml), saved with the same name in the same directory like a Shapefile are not (yet?) immediately loaded.


  1. Hi,
    I am working on a project that requires SLD access from python code.
    Unfortunately I am unfamiliar with SIP.
    Are you able to point out any SIP guides that present it from a QGIS context.
    After searching through my installation directory and only find .SIP files in the Quantum GIS Lisboa\apps\Python27\sip\PyQt directory I have to admit I pretty lost as to where to start.


  2. Are you working on Mac? Not sure about these directories ...

    What I did:
    I added the mentioned methods in the source files python/core/qgsmaplayer.sip and python/core/qgsvectorlayer.sip and rebuilt QGIS.

    I just checked on GitHub and saw that the method "writeSld" is meanwhile included in the master branch:

    I.e. you can grab a nightly QGIS build (or build yourself from source) and at least the second example should work.

  3. And I'm just now finding out about this why....?! THANK YOU!!!