I already know how to change all the headers together, using:
ui->tableWidget->setStyleSheet("QHeaderView::section {background-color:red}");
But I need to change the items individually. 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 unfortunately it will not work on some systems... Qt uses the platform style. For example, my Windows doesn't allow changing 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.