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'

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? – bcallewaert Mar 6 at 14:39
  • Ok, understand...may be the solution should be different. – eurojam Mar 6 at 16:41

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.