[Interest] Customize QTableView selection color

Murphy, Sean smurphy at walbro.com
Fri Feb 5 23:43:24 CET 2016


> > I’m still struggling with how to customize the selection color for items on a
> > QTableView
> 
> I use a QStyledItemDelegate.
> In the paint(painter,option,index) method I create my own QPalette based
> on
> selection etc and then call the base class paint function.
> 
>      QStyleOptionViewItemV4 subop = option;
>      QPalette pal = qApp->palette();
>      if( selected ) {
>         pal.setColor(QPalette::Highlight,Qt::darkGray);
>         pal.setColor(QPalette::WindowText,Qt::white);
>         pal.setColor(QPalette::HighlightedText,Qt::white);
>         pal.setColor(QPalette::Text,Qt::white);
>         subop.state |= QStyle::State_Selected;
>         subop.palette = pal;
>     }
> 
>     BaseClass::paint(painter,subop,index);	// Note: subop.
> 
> >(previously posted as
> > http://lists.qt-project.org/pipermail/interest/2016-January/020760.html). I
> > currently color the rows with custom colors based on the data being shown
> in
> > each row in my model’s data(const QModelIndex &currIndex, int role)
> when role ==
> > Qt::BackgroundRole.

For future readers, which will probably be me again 6 months from now, all I needed was to create a QStyledItemDelegate with paint() reimplemented as follows:

void customStyledItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem subop(option);
    subop.state &= ~(QStyle::State_Selected);
    QStyledItemDelegate::paint(painter, subop, index);
}

Then when an item is selected, it just gets painted the same as the model's Background and Foreground roles was already telling it to.
Sean


More information about the Interest mailing list