QtableWidget VerticalHeader colour depending on row content
-
Hello,
The example shown are anonymized but the logic is the one I used.
I currently have a QTableWidget with 2 columns (first one is the name of a book and the second one its price) and a header whose colour depends on the books price. It is populated as follows:int row {}; for (Book const *book : qAsConst(booksList)) { table->insertRow(row); table->setVerticalHeaderItem( row, getColorizedCell(row, book->price) ); table->setItem(row, 0, getNewCell<QString>(book->name)); table->setItem(row, 1, getNewCell<double>(book->price)); row++; }getColorizedCellcreates a QTableWidgetItem containing first param as text and sets its textColor depending on the second param.getNewCellcreates a QTableWidgetItem and sets its DisplayRole Data to the param sent.
This works well until I enabled sorting (
setSortingEnabled(true)) on the table: when I sort my table the rows are sorted but the vertical header colour doesn't follow the sorting.Is there anyway to make this work natively with the QTableWidget or should I try to find a way to do this using a QTableView/Model ?
-
QTableWidgetis a convenience class, providing an easy way to implement a table with basic features. The implementation above will apply the right colors once, when theQTableWidgetis populated. It won't change if the data is shuffled around.For that purpose, I recommend to implement a
QTableViewwith a custom model, inheriting fromQAbstractTableModel. The model'sdata()override has to return aQVariantfor different roles. The minimum requirement isDisplayRole, which has to contain the data to be displayed in the cell.
TheDecorationRoleis what you're looking for to color a cell according to its content. -
F f222 has marked this topic as solved on