[Interest] Customize QTableView selection color

André Somers andre at familiesomers.nl
Sun Feb 7 10:56:39 CET 2016



Op 05/02/2016 om 23:43 schreef Murphy, Sean:
>>> 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 do exactly what I told you to do on the 5th:
> to create a QStyledItemDelegate with paint() reimplemented as follows:
"A QStyledItemDelegate doing a similar trick would work as well."
>
> void customStyledItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
> {
>      QStyleOptionViewItem subop(option);
" Just make a copy of the style option,"
>      subop.state &= ~(QStyle::State_Selected);
" reset the selection flag in the state variable"
>      QStyledItemDelegate::paint(painter, subop, index);
"and pass that on to the base class."
> }
>
> 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.
>
André




More information about the Interest mailing list