I'm having difficulty performing custom widget rendering in a QListView . Currently, I have a QListView displaying my custom model called PlayQueue based on QAbstractListModel .
This works fine with plain text, but now I would like to display a custom widget for each item. Therefore, I subclassed QStyledItemDelegate to implement the paint method as follows:
void QueueableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { if (option.state & QStyle::State_Selected) painter->fillRect(option.rect, option.palette.highlight()); QWidget *widget = new QPushButton("bonjour"); widget->render(painter); }
The selection background is displayed correctly, but the widget is not displayed. I tried using simple QPainter commands, as in the Qt examples, and this works fine:
void QueueableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const { if (option.state & QStyle::State_Selected) painter->fillRect(option.rect, option.palette.highlight()); if (option.state & QStyle::State_Selected) painter->setPen(option.palette.highlightedText().color()); painter->setFont(QFont("Arial", 10)); painter->drawText(option.rect, Qt::AlignCenter, "Custom drawing"); }
So, I tried some changes, for example:
- Changing
QStyledItemDelegate to QItemDelegate - Adding
painter->save() and painter->restore() around rendering - Adjust widget geometry to an available size
But I am a bit stuck now, I have been looking for some time on the Internet, but cannot find any example of what I want, they all talk about editing a widget (which is much simpler) or user-drawn control (predefined, for example, indicators fulfillment). But here I really need my own widget, which I created, containing some layouts, labels, and bitmaps. Thank you for your help!
I am using Qt 4.7.3 for GCC on Ubuntu 11.04.