I have an attribute table in my layout, defined as follow :

layout = QgsPrintLayout(project)

pdf = QgsProject.instance().mapLayersByName('plan_de_ferme')[0]
pdf_table = QgsLayoutItemAttributeTable.create(layout)
pdf_fields = ['champ','sup','supepnd']
pdf_table.setDisplayedFields(pdf_fields, True)

I would like to rename the fields name displayed in the layout without changing the fields name in the layer.

I tried :

pdf_headers = ['Champ','Superficie (ha)','Superficie épandable (ha)']

Like it's the way to do with a QgsLayoutItemTextTable, but it's not working because "AttributeError: 'QgsLayoutItemAttributeTable' object has no attribute 'setHeading'".


You can use the code snippet below:

pdf_headers = ['Champ','Superficie (ha)','Superficie épandable (ha)']

#retrieve layout table columns
cols = pdf_table.columns()

#construct a new list containing cloned QgsLayoutTableColumn objects
new_cols = [col.clone() for col in cols]

#iterate the cloned columns and use setHeading() method to set each
#column's header cell contents to the corresponding item from pdf_headers
for i, cloned_col in enumerate(new_cols):
#set pdf_table columns from the list of cloned and modified
#column objects with new heading contents

#refresh layout

I tested this code and obtained the following results.

Layout table before:

enter image description here

Layout table after:

enter image description here

While column names in layer remain unchanged:

enter image description here


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.