Using QSS worked for controlling the selection color but with the Style i'm using i had to override the regular QHeaderView::section with a style-sheet as well.
In my case i need to vary the color depending on what state my application is in, so constantly switching the stylesheet might be ineffective in that regard. I managed to override paintSection per your recommendation and can thereby paint the section with a dynamic color. As you mentioned, i could not simply change the palette and had to draw the rectangle and text manually. It doesn't look as nice as I would like but might be good enough in this case. Here is the code:
{
public:
void paintSection
(QPainter* painter,
const QRect
& rect,
int logicalIndex
) const {
QModelIndexList selectedRows = this->selectionModel()->selectedRows();
foreach (const QModelIndex& rowIndex, selectedRows){
if (rowIndex.row() == logicalIndex){
QBrush brush
= qvariant_cast<QBrush>
(rowIndex.
data(Qt
::BackgroundRole));
QString text
= qvariant_cast<QString
(rowIndex.
data(Qt
::DisplayRole));
painter->save();
painter->setBrush(brush.color().darker());
painter->drawRect(rect);
painter->restore();
painter->drawText(rect, Qt::AlignCenter, text);
return;
}
}
QHeaderView::paintSection(painter, rect, logicalIndex
);
}
};
class RowHeader : public QHeaderView
{
public:
void paintSection(QPainter* painter, const QRect& rect, int logicalIndex) const
{
QModelIndexList selectedRows = this->selectionModel()->selectedRows();
foreach (const QModelIndex& rowIndex, selectedRows){
if (rowIndex.row() == logicalIndex){
QBrush brush = qvariant_cast<QBrush>(rowIndex.data(Qt::BackgroundRole));
QString text = qvariant_cast<QString(rowIndex.data(Qt::DisplayRole));
painter->save();
painter->setBrush(brush.color().darker());
painter->drawRect(rect);
painter->restore();
painter->drawText(rect, Qt::AlignCenter, text);
return;
}
}
QHeaderView::paintSection(painter, rect, logicalIndex);
}
};
To copy to clipboard, switch view to plain text mode
Thanks to everyone who responded to the thread!
Bookmarks