Last active
May 31, 2021 15:34
-
-
Save SzieberthAdam/7a728e1df612fd0d30b525782f6e6c52 to your computer and use it in GitHub Desktop.
Python QGIS (PyQGIS) visibility preset manipulation functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Usage:
Tested on QGIS version 3.10.14
Code on GIS.StackExchange (if you star my code here I would appreciate an upvote there too)