Pemdas
Pemdas

Reputation: 543

Drawing QWidgets in Listview with delegate

I am looking for some advice on how to implement a list view with custom content in each row. I have implemented exactly what I want using QLIstWidget, but the QListwidget "eats" any widgets that I pass to it and I don't want that behavior. Also, this list could be "long" and I don't want to allocate 100s of widgets.

The easiest why to describe what I am trying to accomplish is to look at my delegate paint function. This is just a simple example for the sake of this question.

void CustomItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{

    qDebug() << "Painting something" << endl;
    if(index.data().canConvert<CustomModelItem>())
    {
        CustomModellItem item = qvariant_cast<CustmomModelItem>(index.data());
        QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &option, painter, item.getItem());
    }
    else
    {
        qDebug() << "Delegate...something broken 2" << endl;
        QStyledItemDelegate::paint(painter, option, index);

    }
}

CustomModelItem is nothing more than a wrapper structure that holds a pointer a custom widget.

I realize that I could just manual draw the control since it is nothing more than a collection of labels and icons, but I want to draw the item with properties that are defined in a stylesheet. Any advice would be appreciated.

Upvotes: 1

Views: 849

Answers (1)

James Turner
James Turner

Reputation: 2485

If your 'widgets' inside the delegate are simply icons and labels, I would say the simplest and most robust approach is to draw them manually using QPainter in your custom delegate, using the style system if you wish.

Using real widgets is very complex in an item-view, because there is no provision for controlling the life-time of them within the list view. You would need to maintain some data structure of widgets, and position them manually inside paint(), then draw them. Event handling also won't work without some event filters to forward events. I won't say this approach is impossible, but it's a huge amount of work and will likely have bugs.

Note you can define an editor widget and change when the editor is created, for example on any mouse press on the row. This can give you interaction with the row using widgets, but doesn't help with painting.

Upvotes: 2

Related Questions