I know you can loop through the QTableWidgetItems and change their colors but, what if I have used setCellWidget and I have cells that are not QTableWidgetItems. I can't find a simple setRowColor method. It seems like there should be since there are methods for alternating row color and whatnot. Is there a simple way to do this without sub-classing the table's delegate?
Rhetorical question: I just want to change the row color, should I really need a whole new class for that?
I believe with QTableWidget the easiest way setting row color would to iterate through widget items and use setData method to specify the background color, see an example below
for (int column=0; column<4; column++)
{
for (int row = 0; row<5; row++)
{
QTableWidgetItem *newItem = new QTableWidgetItem(tr("%1").arg((row+1)*(column+1)));
newItem->setData(Qt::BackgroundRole, (row%2)>0 ? Qt::red : Qt::blue);
ui->tableWidget->setItem(row, column, newItem);
}
}
if you would want to make it simpler, consider using QTableView widget instead, implement your model (I guess the easiest way is to subclass QStandardItemModel) and hold row colors there. Implement a setRowColor method or/and a slot to specify color for your data rows.
hope this helps, regards
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With