How to change the background color of a specific cell of verticalheader or horizontalheader (qtablewidget)

I would like to know how to change the background color from the headers (horizontal / vertical) from the object QTableWidget on Qt.

I already Know how to change all the headers together, using :

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

But I need change individually the items. Obviously if this is possible .


There are at least 2 ways to solve this problem. Very easy one:

Just use setHeaderData() and set specific colors for specific sections.

QTableView *tview = new QTableView;

QStandardItemModel *md = new QStandardItemModel(4, 4);
for (int row = 0; row < 4; ++row) {
    for (int column = 0; column < 4; ++column) {
        QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column));
        md->setItem(row, column, item);
    }
}
tview->setModel(md);
tview->model()->setHeaderData(0,Qt::Horizontal,QBrush(QColor("red")),Qt::BackgroundRole);
tview->show();

But u nfortunately it will not work on some systems... Qt uses the platform style. For example, my Windows doesn't allow to change header's color. So this code doesn't work on my machine. Fortunately, it can be solved easily with changing global style. So next code works:

//... same code ...
tview->show();
QApplication::setStyle(QStyleFactory::create("Fusion"));

If you don't want to change style, then you should create your own HeaderView. Probably, something similar as here.