You are not logged in.

1

Friday, June 24th 2011, 2:57am

Background color for QTableView columns

Trying to set background color for entire columns (colums 3 & 4 of an 8 column table for example). Thought I could just return the correct QVariant(QBrush) when the data() function of the model is invoked with role = Qt::BackgroundRole but it is never invoked with that role.

The QTableView does use stylesheets to set the default background-color and I am using a QSortFilterProxyModel, although my custom model is a subclass of the QAbstractTableModel.


Any tips would be helpful, I've tried sub-classing the QSortFilterProxyModel and the data() function there never gets invoked with the BackgroundRole either.

TIA
Marc

2

Friday, June 24th 2011, 4:29pm

Did you try style sheets? You can set up styles by class names so if the columns that should be a different color are a different class... I believe there's a property to tell the child controls to draw it's own background(s). That might be what you're seeing in the subclassing you did.

3

Thursday, June 30th 2011, 6:43am

You can also do the following in your custom models data method

Source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
QVariant myModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) // bad index
    {
        return QVariant();
    }

     
    // valid index
      //do your stuff
    switch (role)
    {
    case Qt::DecorationRole: // called to show icons
         //your code
    case Qt::DisplayRole: //called to show text 
        //your code
    case Qt::BackgroundRole: //called to paint the background 
        if(index.column()==3 || index.column()==4)
           // return  your brush color for these columns;
        else
            // return default Brush color;
    default: //some other role we don't really care about
        return QVariant();
    }
}


Hope this helps

regards
-Sukesh