albumdelegate.cpp Example File
mediabrowser/albumdelegate.cpp
#include "albumdelegate.h"
#include <QtGui>
AlbumDelegate::AlbumDelegate(QObject *parent)
: QAbstractItemDelegate(parent)
{
}
AlbumDelegate::~AlbumDelegate()
{
}
void AlbumDelegate::paint(
QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QPen oldPen = painter->pen();
QStyle *style = QApplication::style();
int margin = style->pixelMetric(QStyle::PM_ButtonMargin);
QRect rect = option.rect;
if (option.state & QStyle::State_HasFocus) {
painter->fillRect(rect, option.palette.highlight());
painter->setPen(option.palette.color(QPalette::HighlightedText));
}
rect.adjust(margin, margin, -margin, -margin);
QRect decorationRect = rect;
decorationRect.setRight(decorationRect.left() + option.decorationSize.width());
QPixmap decoration = qvariant_cast<QPixmap>(index.data(Qt::DecorationRole));
if (!decoration.isNull())
style->drawItemPixmap(painter, decorationRect, Qt::AlignCenter, decoration);
else
painter->drawRect(decorationRect);
rect.setLeft(decorationRect.right() + margin);
QString text = index.data(Qt::DisplayRole).toString();
QRect textRect;
painter->drawText(rect, Qt::TextWordWrap, text, &textRect);
rect.setTop(textRect.bottom() + margin);
text = index.data(Artist).toString();
painter->drawText(rect, Qt::TextWordWrap, text, &textRect);
rect.setTop(textRect.bottom() + margin);
QVariant trackCount = index.data(TrackCount);
if (trackCount.isValid()) {
text = trackCount.toInt() != 1
? tr("%1 Songs").arg(trackCount.toInt())
: tr("1 Song");
painter->drawText(rect, Qt::TextWordWrap, text, &textRect);
}
painter->setPen(oldPen);
}
QSize AlbumDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &) const
{
QString placeholder = QLatin1String("This is a longish name");
int margin = QApplication::style()->pixelMetric(QStyle::PM_ButtonMargin);
QSize size = option.decorationSize;
size.rheight() += 2 * margin;
size.rwidth() += 3 * margin + option.fontMetrics.size(0, placeholder).width();
return size;
}
[+] Documentation Feedback