Skip to content

Instantly share code, notes, and snippets.

@SzieberthAdam
Last active May 31, 2021 15:34
Show Gist options
  • Save SzieberthAdam/7a728e1df612fd0d30b525782f6e6c52 to your computer and use it in GitHub Desktop.
Save SzieberthAdam/7a728e1df612fd0d30b525782f6e6c52 to your computer and use it in GitHub Desktop.
Python QGIS (PyQGIS) visibility preset manipulation functions
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
@SzieberthAdam
Copy link
Author

SzieberthAdam commented Sep 14, 2017

Usage:

>>> visibility_presets()
['Test-01']
>>> activate_visibility_preset('Test-01')
True
>>> active_visibility_preset()
'Test-01'

Tested on QGIS version 3.10.14

Code on GIS.StackExchange (if you star my code here I would appreciate an upvote there too)

@SzieberthAdam
Copy link
Author

Note that you might want to refresh the canvas after changing visibility preset:

qgis.utils.iface.mapCanvas().refreshAllLayers()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment