PDA

View Full Version : how to change background color of individual QHeaderView section



413X
10th December 2013, 17:22
Hello,

I have a project with a QTableView and a corresponding QAbstractTableModel. I have implemented a filter that can be applied to multiple columns. I need the column color (just the header section, not the entire column of the QTableView) to change if a filter is being applied to that column. I've made a couple of attempts and did not succeed. I'm starting to wonder if this is even possible.

I tried setting the stylesheet, but it didn't do anything:


QHeaderView::section:selected
{
background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 #00FF00, stop:1 #004C00);
}

I tried connecting the sectionClicked(int) signal in the QHeaderView to the model, to store the lastColumn clicked, and use this in headerData() to return a color if the role== Qt::BackgroundColorRole, but this did not work either.


QVariant OrderTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
...
else if (role == Qt::BackgroundColorRole)
{
if (orientation == Qt::Horizontal) {
if (section == m_nSectionClicked)
{
return QBrush(Qt::darkBlue);
}
else
{
return QBrush(Qt::black);
}
}
}
...
}

Santosh Reddy
11th December 2013, 08:56
I tried setting the stylesheet, but it didn't do anything:



QHeaderView::section:selected
{
background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 #00FF00, stop:1 #004C00);
}

Use ":checked" instead of ":selected"

413X
11th December 2013, 15:41
I tried, but nothing changed. Is a section supposed to be in a "checked" state if it is clicked? Eventually I'd like to have the column header background color change if a filter has been applied to it and alsof if that column is sorted, so I don't think this is possible through style sheets. After reading some other threads I decided to subclass the QHeaderView and override paintSection(). After doing this, I found that I couldn't get at the data because it is in the d-pointer. I couldn't subclass the QHeaderViewPrivate because it is not accessible. I just wanted to copy the code from
QHeaderView::paintSection into the overridden function and make the necessary modifications to change the background color. Am I going about this the wrong way?

Thanks,
Alex

Santosh Reddy
12th December 2013, 05:59
Ok I think you are facing a platform style problem. Refer this thread (http://www.qtcentre.org/threads/13094-QTableView-headerData()-color), it is discussed in there and a solution is also suggested.

413X
12th December 2013, 19:02
Yes, thank you. I read that thread already and tried setting to plastique but it made everything look crappy. And it only works if I remove my style sheet entry for the QHeaderView::section. I have resorted to just putting brackets around the column name if the filter has been applied, which seems fine for now.