I have to make around 1000 maps that represent the same area (it is reclassified satellite image - so raster). Style is the same, only date changes. I figured out how to style all layers in no time and how to print all images in Atlas. I would like to automatize also the process of making Theme (it was called preset in QGIS 2.x) in the layer panel, so I would not need to manually make all the themes I would use later in Atlas. I would like to name them after the name of the layer or raster image (it represents the date of the satellite image).

enter image description here

1 Answer 1


You can do it by running in the Python console the following, using PyQGIS

root = QgsProject.instance().layerTreeRoot()

mapThemesCollection = QgsProject.instance().mapThemeCollection()
mapThemes = mapThemesCollection.mapThemes()
# Where you need to set your images names
# Could be retrieve if only raster names wanted with
# [layer.name() for layer in QgsProject.instance().mapLayers().values() if isinstance(layer, QgsRasterLayer)]
# If you want all layers names and filter them manually
# [layer.name() for layer in QgsProject.instance().mapLayers().values()]
layersToChanges = ['CartoDB Light', 'OpenStreetMap', 'OpenTransports'] # Replace with your list of raster layers instead

for layer in layersToChanges:
    for child in root.children():
        if isinstance(child, QgsLayerTreeGroup):
            print("- group: " + child.name())
        elif isinstance(child, QgsLayerTreeLayer):
            print("- layer: " + child.name() + "  ID: " + child.layerId())
            # Layer you want to tick
            if (child.name() == layer):
                print("Check only once")
            elif child.name() in layersToChanges:
                print("Check the others you want to hide")
    mapThemeRecord = QgsMapThemeCollection.createThemeFromCurrentState(
        # For QGIS 3.18+, instead of above line, use iface.layerTreeView().layerTreeModel()
    mapThemesCollection.insert(layer, mapThemeRecord)

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.