I have successfully created a QListWidget that displays 2 lines of text for each item using this code (adapted from this example):
SessionListDelegate.h
#ifndef SESSIONLISTDELEGATE_H_
#define SESSIONLISTDELEGATE_H_
#include <QPainter>
#include <QAbstractItemDelegate>
class SessionListDelegate : public QAbstractItemDelegate
{
public:
SessionListDelegate(QObject *parent = 0, QStyle *style);
virtual ~SessionListDelegate();
void paint (QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const;
QSize sizeHint (const QStyleOptionViewItem & option, const QModelIndex & index) const;
private:
};
#endif /* SESSIONLISTDELEGATE_H_ */
SessionListDelegate.cpp
#include "SessionListDelegate.h"
SessionListDelegate::SessionListDelegate(QObject *parent)
: QAbstractItemDelegate(parent)
{
this->_parent = parent;
}
void SessionListDelegate::paint(QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
QRect r = option.rect;
QPen fontPen(QColor::fromRgb(51,51,51), 1, Qt::SolidLine);
if(option.state & QStyle::State_Selected)
{
painter->fillRect(option.rect, option.palette.color(QPalette::Highlight));
}
painter->setPen(fontPen);
QString date = index.data(Qt::DisplayRole).toString();
QString description = index.data(Qt::UserRole).toString();
int imageSpace = 10;
r = option.rect.adjusted(imageSpace, 0, -10, -30);
painter->setFont(QFont( "Lucida Grande", 24, QFont::Normal));
painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignBottom|Qt::AlignLeft, date, &r);
r = option.rect.adjusted(imageSpace, 30, -10, 0);
painter->setFont(QFont( "Lucida Grande", 18, QFont::Normal));
painter->drawText(r.left(), r.top(), r.width(), r.height(), Qt::AlignLeft, description, &r);
}
QSize SessionListDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const
{
return QSize(200, 60); // very dumb value
}
SessionListDelegate::~SessionListDelegate()
{
// TODO Auto-generated destructor stub
}
Calling code in mainapp.cpp:
ui.myList->setItemDelegate(new SessionListDelegate(ui.myList));
Now, in the main QWidget form of my application UI, I have defined a style sheet which contains a style for all QListViews for the form:
QListView::item:selected {
color: black;
background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0 rgba(255, 255, 80, 255), stop:1 rgba(255, 255, 255, 255));
}
I would like to apply this style to the customized ListWidget, but I can’t think of a way to make that happen. It seems like it should be a pretty common thing to do, but I can’t find any examples anywhere.
I think you should inherit from
QStyledItemDelegateinstead ofQAbstractItemDelegate. From the Qt documentation: