QTableWidget: Set specific row's color
-
Hi,
I am using QTableWidget since it offers many features with respect to custom cell widgets animation etc. I want to set the color of a specific row at runtime. How do I do this?
Is creating a delegate the only way to do this? How can it be done with delegates?
-
@sunil-nair
It can done withQTableWidgetItem
as follows:-
Or stylesheet
QTableWidget::item { background-color: red; }
-
@p3c0 ```
ui->tablewidget-setitem(row, column, new QTableWidgetItem (string) ) ;
ui->tablewidget-item(row, column)->setbackground(QBrush(QColor(250,0,0))):This code has no impact on the color of the qwidgetitem. I also tried ``` ui->tablewidget-item(row, column) ->setData(Qt::BackgroundRole, QColor (250,0,0))
Even that doesn't work. I cannot use stylesheets since I want to change the color of a specific row at runtime.
-
@sunil-nair Check this example. To color the entire row you will need to iterate through all the cells and apply the same logic.
-
void setRowBackground(const QBrush& brush, QAbstractItemModel* model, int row, const QModelIndex& parent = QModelIndex() ){ if(!model || row<0 || row>=model->rowCount(parent)) return; if(parent.isValid() && parent.model() != model){ return; for(int i=0;i<model->columnCount(parent);++i) Q_ASSUME(model->setData(model->index(row,i,parent),brush,Qt::BackgroundRole)); }
now you can use it with:
setRowBackground(QColor(250,0,0),ui->tablewidget->model(),row);
-
@VRonin thanks for the reply. I tried your code. I am going into the model->setData block but I am not able to see any change in color. Do I need to do any more settings. I tried to also set a qstyleditemdelegate to my qtablewidget but the color doesn't change.
-
I am using a qabstractitemmodel only. But it is not changing the row color.
-
@sunil.nair said in QTableWidget: Set specific row's color:
I am using a qabstractitemmodel only
Your problem is in there then. could you post the code of your model?
-
@VRonin hey it works. I created a separate qt project and it's working there. I will see if I am doing something wrong in my project.
Actually the row to which I am trying to set a background color also has some color set to it in table widget stylesheet. Also tablewidget items also have a background color. I will check there. Thanks again.