0

I have a scenario where I want to paint an item in a QTreeView differently when it is collapsed, but I see no way of doing so as neither the model, nor the delegate have any knowledge of the collapsed/expanded state of the item in the view.

Note that this isn't just a case of wanting it styled differently; I need to pull data from the model per index to know what to paint, so stylesheets aren't going to cut it.

Parker Coates
  • 8,520
  • 3
  • 31
  • 37

1 Answers1

2

This isn't easy but I think I can help. You need to create a delegate where you will have also a reference of your model (and a proxy if you have one).

Here is what I've made for my music player. Note that I used QStyledItemDelegate and not QAbstractItemDelegate:

    void YourItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStandardItem *item = _model->itemFromIndex(_proxy->mapToSource(index));
    switch (item->type()) {
    case Miam::IT_Album:
        this->paintRect(painter, o);
        this->drawAlbum(painter, o, static_cast<AlbumItem*>(item));
        break;
    case Miam::IT_Artist:
        this->paintRect(painter, o);
        this->drawArtist(painter, o, static_cast<ArtistItem*>(item));
        break;
    case Miam::IT_Disc:
        this->paintRect(painter, o);
        this->drawDisc(painter, o, static_cast<DiscItem*>(item));
        break;
    case Miam::IT_Separator:
        this->drawLetter(painter, o, static_cast<SeparatorItem*>(item));
        break;
    case Miam::IT_Track: {
        /// etc
        break;
    }
    default:
        QStyledItemDelegate::paint(painter, o, index);
        break;
    }
}

Then, in the QTreeView class you have:

bool QTreeView::isExpanded(const QModelIndex & index) const

You can check if your item is expanded or not to do some special painting operations.

With some hard work, you can achieve something like this: Custom delegate in QTreeView

MBach
  • 1,647
  • 16
  • 30
  • I had just come up with the idea of letting the delegate hold on to a copy pointer to the QTreeView. Since there's a 1:1 relationship from view to delegate in my case, this should be completely safe, even if it does break Qt's model/view design. Thanks! – Parker Coates Sep 18 '15 at 10:09