Search code examples
qtqtreewidgetqtreewidgetitemqitemdelegate

Set QItemDelegate on a particular QTreeWidgetItem


Is it possible to set a QItemDelegate on a particular QTreeWidgetItem? I need to color some of the QTreeWidgetItems with a particular color.

I assume it is possible as we have QAbstractItemView::setItemDelegateForRow but I can't figure out how. I can't use QAbstractItemView::setItemDelegateForRow because I need to set a custom delegate on a child row inside the QTreeWidget.

Does anyone know a solution for that?


Solution

  • You can access the QTreeWidget from you delegate's paint routine to check if a condition for painting the background is met

    void custom_delegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
    {
        const QTreeWidget* tree_widget = qobject_cast<const QTreeWidget*>(qstyleoption_cast<const QStyleOptionViewItemV3*>(&option)->widget);
        ....
    }
    

    or you store something in the QModelIndex UserData as Chernobyl suggested. In that case I would however create an enum for flags (if this is applicable in your case):

    enum custom_painter_flags{
        paint_default = 0,
        paint_background = 1
    };
    
    void somewhere_creating_the_items()
    {
        QTreeWidgetItem* newitem = new QTreeWidgetItem(...);
        newitem->setData(0, Qt::UserRole, QVariant::fromValue<int>(custom_painter_flags::paint_background));
    }
    
    void custom_delegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
    {
        custom_painter_flags painter_flags = static_cast<painter>(index.data(Qt::UserRole).value<int>());
    
        if(painter_flags & paint_background){
            ....
        }
    }
    

    Unfortunately I have not much time right now so this is thrown together pretty quick. Feel free to edit if you find any errors.