4

I'm trying to create a label in the QGIS composer which automatically displays the Composer name (or window name may do the same thing).

For example, I can display the project filename by using @project_filename but I cannot determine how to display the composer name.

1 Answer 1

3

You can do it either automatically or manually.


Automatically

Select your label then go to:

Item Properties > Main properties > Insert an expression...

Click the Function Editor tab and use something like the following:

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

@qgsfunction(args='auto', group='Custom')
def comp_name(feature, parent):
    active_Composer = qgis.utils.iface.activeComposers()
    composer = active_Composer[0]
    return composer.composerWindow().windowTitle()

Function editor

Then use an expression like:

[%comp_name()%]

Result

Note that this returns the composer name of the first composer window. If you want to return the title of the current composer that is displayed, you could use the following function:

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

@qgsfunction(args='auto', group='Custom')
def comp_name(feature, parent):
    for composer in qgis.utils.iface.activeComposers():
        if composer.isActiveWindow():
            return composer.composerWindow().windowTitle()

Manually

In the Composition tab, scroll down until you see the Variables section. Create a new variable name (e.g. "composer_name") and value:

Add variable

Then in your label, use an expression like:

[% var('composer_name')%]

Result

5
  • The automatic method you have outlined above works, however as you have noted, this appears to return the name of the first composer window. Is it possible to return the title of the composer window currently displayed?
    – Jason
    May 22, 2017 at 12:51
  • @Jason - I tried searching for a method to read the current composer window but couldn't find much. Will check again :)
    – Joseph
    May 22, 2017 at 13:01
  • @Jason - I've edited the post to include a function which would show the title of the currently displayed composer window. In other words, if the active window is not a composer, the title will not be returned. I'm not sure if there is another method to achieve this...
    – Joseph
    May 22, 2017 at 13:33
  • That works for my purposes as I only need the composer name to display when I export as PDF. Therefore I will always have to activate the window anyway to export as PDF.
    – Jason
    May 22, 2017 at 14:09
  • @Jason - Glad it works for your use-case! It would certainly be a nice feature to add as a variable expression :)
    – Joseph
    May 22, 2017 at 14:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.