QGIS – Dynamic Height Value from a LayoutItem Using a PyQGIS Function

expressionlayoutsprint-composerpyqgisqgis

I'm trying to make a function that allows me to get the dynamic height of a LayoutItem in the print composer. I'm working in QGIS 3.16.

The following code works well to get an item height, when I run it as a script in the Python console.

#defining variables
layout_name = "LayoutName"
item_name = "ItemName"

#getting the layout
manager = QgsProject.instance().layoutManager()
layout = manager.layoutByName(layout_name)

#geting the layoutItem --> getting item size --> getting item height
get_item = layout.itemById(item_name)
get_item_size = get_item.sizeWithUnits()
get_item_height = get_item_size.height()

print(get_item_height)

I want to change this code in a way, so I can get the item height dynamically instead and so I can use the height as a variable for defining the height of other items in my layout (like it's possible to do with the variable @layout_pageheight).

I would assume that I could just change the code in this way:


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

@qgsfunction(args= 'auto' , group='Custom')
def GetDynamicItemHeight (LayoutName , ItemName): 
    #variables
    layout_name = LayoutName
    item_name = ItemName

    #getting the layout
    manager = QgsProject.instance().layoutManager()
    layout = manager.layoutByName(layout_name)

    #geting the layoutItem --> getting item size --> getting item height
    get_item = layout.itemById(item_name)
    get_item_size = get_item.sizeWithUnits()
    get_item_height = get_item_size.height()

    #returning the height value
    return get_item_height

Then go to an expression editor in the layout and enter the following:

GetDynamicItemHeight(@layout_name, "ItemName") 

And I would get the dynamic height of the specified item. Only problem is – it doesn't work.

Can anyone help to figure out what needs to be changed?

Best Answer

Add feature, parent parameters to the definition line. Although not needed in the context of the layout, they are mandatory. There are some issues in GitHub.

    ...

@qgsfunction(args= 'auto' , group='Custom')
def GetDynamicItemHeight (LayoutName , ItemName, feature, parent):
    ... 
    ...

And use ' instead of " in expression for ItemName

GetDynamicItemHeight(@layout_name, 'ItemName')

enter image description here

Related Question