How to automatically make the title of your print equal to the name of the printed layer? Tried by using the next piece of code, but it doesn't work (QGIS 3.X):

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

@qgsfunction(args='auto', group='Custom')
def func(feature, parent):
    root = QgsProject.instance().layerTreeRoot()
    layer = qgis.utils.iface.activeLayer()
    lyr = root.findLayer(QgsProject.instance().mapLayersByName(layer.name())[0].id())
    group = lyr.parent().name()
    if group != '':
        return lyr.parent().name()
        return 'Group not found'

2 Answers 2


to get the active layer name, you can only use this part of your code:

def activeLayerName(feature, parent):
    layer = qgis.utils.iface.activeLayer().name()
    return layer
  • What I was trying to ask was this: when I print a layer I want the layer its name at the top of the print. When I need to print e.g. 50 different layers, I don't want to manually adjust the title in the printed page each time. you see? Commented Mar 6, 2019 at 14:39
  • Ok, understand...may be the solution should be different.
    – eurojam
    Commented Mar 6, 2019 at 16:41

To include the printed layer in a text in your QGIS layout template, you can use an expression to dynamically retrieve the layer name and insert it into the text element.

Here are the steps:

Add a Text element to your QGIS layout template where you want the layer name to appear.

Double click on the text element to enter edit mode.

In the text editor, type the following expression:

[% @layer_name %]

Click "OK" to save the text element.

Now, when you export or print the layout using this template, the text element will automatically display the name of the layer. If you have multiple layers and want to include the names of all of them, you can modify the expression to include the names of all the layers. For example:

[% @layer_name || ', ' || @atlas_pagename %]

This will concatenate the names of all layers, separated by commas. You can adjust the expression as needed to achieve the desired output.

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.