Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to change background color of row in a QTableWidget?

Tags:

qt

qt4

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?

like image 774
Gagege Avatar asked Feb 18 '11 17:02

Gagege


1 Answers

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

like image 150
serge_gubenko Avatar answered Sep 28 '22 06:09

serge_gubenko