def activate_visibility_preset(preset_name, *, project=None, coll=None):
"""Activates a visibility preset by its name.
Return a boolean indicating success."""
# https://github.com/qgis/QGIS/blob/f044c95fd8927d86967ce8af3930bdc7523095fa/src/app/qgsmapthemes.cpp#L138
if project is None:
project = qgis.core.QgsProject.instance()
if coll is None:
coll = project.mapThemeCollection()
if not coll.hasMapTheme(preset_name):
return False
root = project.layerTreeRoot()
model = qgis.utils.iface.layerTreeView().model()
coll.applyTheme(preset_name, root, model)
return True
def active_visibility_preset(*, project=None, coll=None):
"""Return the name of the active visibility preset or
None if no active visibility preset."""
# https://github.com/qgis/QGIS/blob/f044c95fd8927d86967ce8af3930bdc7523095fa/src/app/qgsmapthemes.cpp#L210
if project is None:
project = qgis.core.QgsProject.instance()
if coll is None:
coll = project.mapThemeCollection()
root = project.layerTreeRoot()
model = qgis.utils.iface.layerTreeView().model()
curr_mapthemecollection = coll.createThemeFromCurrentState(root, model)
for preset_name in visibility_presets(project=project, coll=coll):
checking_preset = coll.mapThemeState(preset_name)
if checking_preset == curr_mapthemecollection:
return preset_name
def visibility_presets(*, project=None, coll=None):
"""Return the names of the visibility presets in a list."""
# https://github.com/qgis/QGIS/blob/f044c95fd8927d86967ce8af3930bdc7523095fa/src/app/qgsmapthemes.cpp#L149
if project is None:
project = qgis.core.QgsProject.instance()
if coll is None:
coll = project.mapThemeCollection()
preset_names = coll.mapThemes()
return preset_names
Usage:
>>> visibility_presets()
['Test-01']
>>> activate_visibility_preset('Test-01')
True
>>> active_visibility_preset()
'Test-01'
Tested on QGIS 3.10.14
Note that you might want to refresh the canvas after changing visibility preset:
qgis.utils.iface.mapCanvas().refreshAllLayers()
Code on GitHub Gist (if you upvote here I would appreciate a star there too)