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

QStyledItemDelegate with custom paint() background color from selection / item-type



  • Hello,

    I have a StyledItemDelegate with a custom paint method

    void myDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,const QModelIndex &index) const
    {
        QWidget* editor = m_my_editor_widegt;      
    
        QStyleOptionViewItem opt = option;
        QStyledItemDelegate::initStyleOption(&opt, index);
    
        setDummyEditorData(editor, index);
        editor->resize(opt.rect.size());
        editor->setPalette(opt.palette);
        QPixmap pixmap(opt.rect.size());
        editor->render(&pixmap);
        painter->drawPixmap(opt.rect,pixmap);
    }
    

    the editor is a QWidget with other stuff in there (label, checkbox, lineedit, ...)
    The rowcolor of my view is dependent of the item type and is provided by ItemModel::data(Qt::BackgroundColorRole).

    How do I tell the delegate to draw the widget with the right color?



  • Hi @gde23,

    I think it should be something like that (not tested):

    QColor background = index.data(Qt::BackgroundRole).toColor();
    opt.palette.setColor(QPalette::Active, QPalette::Window, background)
    


  • @Gojir4 said in QStyledItemDelegate with custom paint() background color from selection / item-type:

    QColor background = index.data(Qt::BackgroundRole).toColor();
    opt.palette.setColor(QPalette::Active, QPalette::Window, background)

    I've tried that, but that results in the widget looking totally colorful (each pixel random) like uninitialized memory.

    EDIT: Now its working, had to paint it with the background first since the background color of the items has alpha



  • @gde23 Glad it works !

    EDIT: Now its working, had to paint it with the background first since the background color of the items has alpha

    Sorry but I don't understand what do you mean ?


Log in to reply