17

The following is what I've currently tried. The header text changes color correctly but the background will not change from the default.

template<typename T>
inline QVariant TableModel<T>::headerData(int section, Qt::Orientation orientation, int role) const
{
    //...
    else if(role == Qt::BackgroundRole) {
        return QBrush(m_display.headerBackground);
    }
    //...
}

How can I set the background color?

andre
  • 7,018
  • 4
  • 43
  • 75
  • Is this value constant -- is same brush returned each time this function is ever called on an instance of a model? If not, are you emitting relevant signals to notify the view that the header data has changed? – Kuba hasn't forgotten Monica Jul 12 '12 at 22:40

2 Answers2

35

You can set the style sheet on the QTableView

ui->tableView->setStyleSheet("QHeaderView::section { background-color:red }");

for more info see http://doc.qt.io/qt-4.8/stylesheet-examples.html

Bowdzone
  • 3,827
  • 11
  • 39
  • 52
Jimmy
  • 6,001
  • 1
  • 22
  • 21
  • This still leaves the "corner" in-between the vertical and horizontal header un styled, what is that called? its different then the table content as well – Jim Feb 06 '20 at 18:41
  • 1
    @Jim The corner widget in a QTableView is implemented as a QAbstractButton and can be styled using the "QTableView QTableCornerButton::section" selector. (from https://doc.qt.io/qt-5/stylesheet-reference.html#qtableview-widget) – Matt Binford Mar 16 '21 at 15:59
2

Here's an alternative solution.

MyTableView::MyTableView( QWidget* parent ) : QTableView( parent )
{
    ...
    // Make a copy of the current header palette.
    QPalette palette = horizontalHeader()->palette();

    // Set the normal/active, background color
    // QPalette::Background is obsolete, use QPalette::Window
    palette.setColor( QPalette::Normal, QPalette::Window, Qt::red );

    // Set the palette on the header.
    horizontalHeader()->setPalette( palette );
}
Matthew
  • 2,759
  • 18
  • 28