Issue
Using Qt 5.7.1 along with Stylesheet how can I make the row header section background color follow the same alternating pattern of the row cells
My stylesheet is
QTableView {
alternate-background-color: lightblue;
background-color: grey;
}
QTableView::item:selected {
background-color: lightgreen;
}
QTableView QTableCornerButton::section {
background-color: transparent;
border: 0px ;
}
QHeaderView {
background-color: grey;
alternate-background-color: lightblue;
}
QHeaderView::section {
background-color: transparent;
alternate-background-color: lightblue;
}
I’ve tried to enable it through
ui->tableWidget3->setAlternatingRowColors(true);
ui->tableWidget3->verticalHeader()->setAlternatingRowColors(true);
Unfortunately it didn’t work.
Solution
You can implement this behavior not with qss but with subclassing of QHeaderView
. For example:
#include <QHeaderView>
class AlterHeader : public QHeaderView
{
Q_OBJECT
public:
explicit AlterHeader(Qt::Orientation orientation, QWidget *parent = nullptr);
protected:
void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const;
};
void AlterHeader::paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
Qt::Alignment align = (Qt::AlignHCenter | Qt::AlignVCenter);
if (logicalIndex % 2 > 0) {
painter->fillRect(rect, QColor("lightblue"));
} else {
painter->fillRect(rect, QColor("grey"));
}
painter->drawText(rect, align, QString::number(logicalIndex));
}
And using:
AlterHeader *header = new AlterHeader(Qt::Vertical, ui->tableWidget);
ui->tableWidget->setVerticalHeader(header);
Answered By – Serhiy Kulish
Answer Checked By – David Goodson (BugsFixing Volunteer)