Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

When using a custom delegate to paint the items of a QTableWidget, how can the delegate be configured to use the correct background colour for selected items?



  • Hi,

    Normally, when a QTableWidget item is selected, the background appears dark blue, but when I use a custom delegate to paint the items (taken from a Stack Overflow post, https://stackoverflow.com/questions/1956542/how-to-make-item-view-render-rich-html-text-in-qt/1956781#1956781) the background appears light blue instead.

    What do I need to do to match the original behaviour when using the delegate?

    Thanks.


  • Lifetime Qt Champion

    Hi
    Add some extra code to the painting (set the brush)

    void HtmlDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                             const QModelIndex &index) const
    {
        QStyleOptionViewItemV4 optionV4 = option;
        initStyleOption(&optionV4, index);
    
        QStyle *style = optionV4.widget ? optionV4.widget->style() : QApplication::style();
    
        QTextDocument doc;
        doc.setHtml(optionV4.text);
    
        /// Painting item without text
        optionV4.text = QString();
    
        if (option.state & QStyle::State_Selected) { //////////// new
            painter->setPen(Qt::white);
            painter->setBrush(option.palette.highlightedText());
        }
    
        style->drawControl(QStyle::CE_ItemViewItem, &option, painter, option.widget); // slightly changed
    
        QAbstractTextDocumentLayout::PaintContext ctx;
    
        // Highlighting text if item is selected
        if (optionV4.state & QStyle::State_Selected) {
            ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active,
                                                                        QPalette::HighlightedText));
            ctx.palette.setColor(QPalette::Highlight, Qt::green);
            ctx.palette.setColor(QPalette::Base, Qt::green);
        }
    
        QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4);
        painter->save();
        painter->translate(textRect.topLeft());
        painter->setClipRect(textRect.translated(-textRect.topLeft()));
        doc.documentLayout()->draw(painter, ctx);
        painter->restore();
    }
    
    

    alt text



  • @mrjj Thanks! That's fixed it.


Log in to reply