Important: Please read the Qt Code of Conduct -

QStyledItemDelegate with paint() and rowColor from Qt::BackgroundColorRole

  • Hello,
    I have a QStyledItemDelegate with the following implementation of paint()

    void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
        const QModelIndex &index) const
        .... here the editor is generated and so on
        // now the painting part begins
        QStyleOptionViewItem option_widget = option;
        QStyledItemDelegate::initStyleOption(&option_widget, index);
        // where to set the color???
        QColor background = index.model()->data(index, Qt::BackgroundColorRole).value<QColor>();
        // this is needed so the selection is painted correctly, otherwise the row-selection is not visible
        QStyleOptionViewItem option_widget_backgrund = option;
        QStyledItemDelegate::paint(painter, option_widget_backgrund, QModelIndex());
        // start drawing ------------------------------------------------------------
        editor->render(painter, QPoint(), QRegion(), QWidget::DrawChildren);

    What I am doing here is first call QStyledItemDelegate::paint(painter, option_widget_backgrund, QModelIndex()); with an invalid index to paint the selection background.
    This works but is it really the correct way to paint the selection coloring??

    Now besides the selection coloring I want to colour the background of some rows as specified by Qt::BackgroundColorRole in the model.
    Where do I set this color?

  • Lifetime Qt Champion

    QModelIndex has a data() function:

  • @Christian-Ehrlicher: but what do I do with the color data? My problem is that I do not know where to set it.

  • Lifetime Qt Champion

    Setting data in the model can be done with QAbstractItemModel::setData()

  • Maybe I have not explained clearly what my problem is.

    I already have all the data in the model and I also have implemented the setData() and data() functions and so on.
    However now I want to have an QStyledItemDelegate in my View that has a custom paint() function.

    From the model I get the background color for each item with data(index, Qt::BackgroundColorRole)
    When I do not use delegates it also paints the color correctly.
    I just do not know how to use the color for the background in my custom paint() function.

  • You don't really have a custom paint. You are just delegating the paint to a widget (editor->render()). You need to set up said widget to support changing its background

Log in to reply