How to change background color of QTableView header

The following is what I was trying now. The title text changes color correctly, but the background will not change by 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 to set the background color?

+5
source share
2 answers

You can set the stylesheet in QTableView

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

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

+12
source

Here is 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 );
}
+4
source

All Articles