I would like to store QGIS Map themes to be used later. In my workflow, I use a plugin which imports many (grouped) layers. Each layer contains several styles that I can switch between. I want to switch some of the styles of the layers, and then store these settings as a Map Theme. This works great, the problem is that next time I use the same plugin (in a new QGIS project), I don't have the Map Themes available as they are not stored.

I thought I found a solution to store the Map Themes using PyQGIS, but I can't get it to work. I found this thread: Export theme and its associated layers in xml file in PyQGIS

I add a Map Theme, and then run the following code

doc = QDomDocument()
mapThemesCollection = QgsProject.instance().mapThemeCollection()
print(mapThemesCollection.mapThemes()) # I see the names of my themes printed

The doc QDomDocument still seems to be empty since doc.toString() prints an empty string. Also, how do I save this as an XML file to be read later with mapThemesCollection.readXml(doc)

If there are other solutions to re-use themes within different projects I am also glad to hear about them.

1 Answer 1


You need a qgis child element to your QDomDocument according to the source code

doc = QDomDocument()
mapThemesCollection = QgsProject.instance().mapThemeCollection()

To read it in a new QDomDocument

doc1 = QDomDocument()

To read or write file, you can either choose Python open method or Qt/PyQt QFile

  • 1
    Thank you, this answered the technical part of my question. I am now able to view the XML of the Map Themes. Unfortunately, I found out that layers are stored with their id, which is different every time I load the layers from different files. I'm now trying to solve my problem by recreating the Map Themes using PyQGIS. Unfortunately, I am not able to set the style of layers (only create state from current), nor if groups are checked or not (MapThemeRecord.hasCheckedStateInfo() is not available in python bindings). Anyone knows a way to store style, checked & collapsed of groups and layers?
    – Eversa
    Jun 10, 2021 at 15:09
  • It's more than one question. The website is for Q&A with one focus. Ask another question with only one question
    – ThomasG77
    Jun 10, 2021 at 15:14

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.