4

I'm using QGIS 3.2.2 and Python. I would like to read out which map theme I currently use.

enter image description here

I know the following method provides me a list of defined map themes ('Theme1', 'Theme2'):

QgsProject.instance().mapThemeCollection().mapThemes() 

I don't know any method which provides me with the map theme name used itself.

I tried to use iface.mapCanvas().theme() but it always returns an empty string.

  • that looks right according to the freshest documentation. What happens if you set the theme from code rather than using the GUI? Also, try iface.MapCanvas().theme (without the brackets)? – Steven Kay Aug 22 '18 at 8:54
  • When I set the theme directly with,e,g, iface.mapCanvas().setTheme('Theme2') , iface.mapCanvas().theme() provides me the correct theme name. But the flag is not set correctly in the GUI, its always unchanged. Must be a bug. For my workflow I need the GUI solution. – DG85 Aug 22 '18 at 9:10
  • 1
    I have created a bug report on qgis redmine. – DG85 Aug 23 '18 at 9:52
  • A link would be helpful then: issues.qgis.org/issues/19674 – SzieberthAdam Sep 11 '18 at 15:24
2

After much research, I found a solution.

To view current map theme, you can use this code (inspired by https://issues.qgis.org/issues/19674):

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def myTheme(feature, parent):
    QgsI = QgsProject.instance()
    mTC = QgsI.mapThemeCollection()
    mTs = mTC.mapThemes()
    root = QgsI.layerTreeRoot()
    model = QgsLayerTreeModel(root)
    goodTheme = mTC.createThemeFromCurrentState( root, model )
    for r in mTs:
        if mTC.mapThemeState(r) == goodTheme :
            return r

To view current theme in layout, you can use this code:

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def myLayoutTheme(currLayoutName, feature, parent):
    i = QgsProject.instance()
    lm = i.layoutManager()
    """l = lm.layouts()[0]"""
    l = lm.layoutByName(currLayoutName)
    rmap = l.referenceMap()
    return rmap.followVisibilityPresetName()

lm.layouts()[0] it's not good things but i have only one layout

UPDATE : I use layoutByName() instead of layouts()

You can now use myLayoutTheme( @layout_name ) to view current theme in current layout

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.