3

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

layout = QgsPrintLayout(project)
layout.initializeDefaults()
QgsProject.instance().layoutManager().addLayout(layout)

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

I would like to set a background color for the header row and all even rows, as follow :

enter image description here

I can use pdf_table.setBackgroundColor(QColor(166, 206, 227, 255)) to apply a blue color for the whole attribute table but it's not what I am looking for.

attribute table 2

I think I should use QgsLayoutTable Class and QgsLayoutTableStyle Class. According to its definition, the class QgsLayoutTable has a method called setCellStyle that requires two inputs : void setCellStyle( CellStyleGroup group, const QgsLayoutTableStyle &style )

CellStyleGroup is a public type of QgsLayoutTable, defined ad follow in the first link: enter image description here

I don't know by what to replace "const QgsLayoutTableStyle &style"

I tried

pdf_table.setCellStyle(qgis.core.QgsLayoutTable.CellStyleGroup.EvenRows,
                        cellBackgroundColor(QColor( 166, 206, 227, 255 )))

but I get the following error: "NameError: name 'cellBackgroundColor' is not defined",

and

pdf_table.setCellStyle(qgis.core.QgsLayoutTable.CellStyleGroup.EvenRows, 
                       QgsLayoutTableStyle().cellBackgroundColor(QColor( 166, 206, 227, 255 )))

but I get the error "TypeError: 'QColor' object is not callable",

and

pdf_table.setCellStyle(qgis.core.QgsLayoutTable.CellStyleGroup.EvenRows, 
                       QgsLayoutTableStyle.cellBackgroundColor(QColor( 166, 206, 227, 255 )))

returns "AttributeError: 'QgsLayoutTableStyle' object attribute 'cellBackgroundColor' is an instance attribute".

Like I'm not familiar with the several Python definitions, I don't understand what these means.

0
4

You need the following short snippet of code to construct a QgsLayoutTableStyle() object, set its enabled and cellBackgroundColor attributes, and then pass it as the 2nd argument to the setCellStyle() method.

table_style = QgsLayoutTableStyle()
table_style.enabled = True
table_style.cellBackgroundColor = QColor(166, 206, 227, 255)
pdf_table.setCellStyle(QgsLayoutTable.EvenRows, table_style)
layout.refresh()

Example result:

enter image description here

1

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.