Gagege
Gagege

Reputation: 670

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

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?

Upvotes: 7

Views: 19915

Answers (2)

serge_gubenko
serge_gubenko

Reputation: 20492

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

Upvotes: 5

Liz
Liz

Reputation: 8968

You can add a style sheet to your QTableWidget something like this:

QTableWidget::item {
    background-color: rgb(255, 85, 127);
}

You can set this is code as well as follows:

QString _CustomStyle = QString(
      "QTableWidget::item {"
      "background-color: rgba(162, 186, 60);"
      "}";
tableWidget->setStyleSheet(_CustomStyle);

Use your own color RGB (obviously).

Upvotes: 3

Related Questions