Qt: QTableWidget/QTableView alternating row colors in full viewport

10,614

Solution 1

Why don't you use Qt QSS for this? It working just fine. Have a look here : http://www.qtcentre.org/threads/42211-QTableWidget-alternating-background-color?p=263046#post263046

myTable->setAlternatingRowColors(true);
myTable->setStyleSheet("alternate-background-color: yellow;background-color: red;");

Solution 2

You could reimplement data() method of your model like this:

QVariant MyModel::data(const QModelIndex& index, int role) const
{
    if(role == Qt::BackgroundColorRole)
        return color;
    ...
}

It should be possible to do the same with a delegate using setModelData().

Share:
10,614

Related videos on Youtube

Zumteufel
Author by

Zumteufel

Updated on September 15, 2022

Comments

  • Zumteufel
    Zumteufel over 1 year

    I have a QTableView containing data rows from a database. However, setting setAlternatingRowColors(true) only alternates row colors that has data - the rest of the table is just white, which is not the behaviour you'd expect (look in the bookmark list of any browser, for example - empty rows has alternating colors).

    Does anyone know a workarund or an alternative to the table views supplied by Qt? I've fiddled with stylesheets and item delegates, same result.

    • Zumteufel
      Zumteufel almost 11 years
      I ended up using a QTreeView / QTreeWidget instead. It's easy making them behave like tables. However, obviously a QTable* and a QTree* should behave in the same way in regards to filling out empty rows with alternating colors, but...
  • Funt
    Funt over 10 years
    Should. In my case it works. You can try it will not take much time.
  • swdev
    swdev almost 10 years
    alternating color is simple, but making the alternating color fill the entire rows when the data is not enough, is different matter