Analogue to saving a layers symbology into a *.qml file I would like to have the xml content of a layers symbology in a python string (or QDomDocument). I think the method QgsVectorLayer().writeSymbology() does what I'm after, but I'm unsure how to use its parameters properly. Any suggestions?


This works with QgsMapLayer().exportNamedStyle() the following way (here for the active layer):

>>> from PyQt4.QtXml import QDomDocument
>>> d = QDomDocument()
>>> iface.activeLayer().exportNamedStyle(d, '')
>>> s = d.toString()
>>> s
u'<!DOCTYPE qgis PUBLIC \'http://mrcc.com/qgis.dtd\' \'SYSTEM\'>\n<qgis version="2.18.21" simplifyAlgorithm="0" minimumScale="0" ...

(Works for QGIS 2.18 and 3.4)

  • For PyQGIS 3.18, the error message string isn't an Input parameter anymore, but a return from the exportNamedStyle() function (same for importNamedStyle()). Otherwise, this solution still works. See QgsMapLayer API documentation. Apr 1 at 8: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.