woodtluk
10th August 2010, 11:42
Hi everybody
I try to create my own delegate for a list view.
I'd like to draw my list items similar to the default behaviour. That is a picture on the left side and than a text. But the text is in html format to support some formation as different text size and text colour.
So I implemented my ouwn QStyledItemDelegate::paint method. But my items are not painted properly.
The first item is painted as supposed. But for the other items only the image is painted.
When I scroll the list view then sometimes other items are painted. But the text is drawn to far left and under the images.
void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
if(!index.isValid())
return;
painter->save();
// handle selection
if(option.state & QStyle::State_Selected){
painter->fillRect(option.rect, option.palette.color(QPalette::Highlight));
}
// get the oicture for the decoration role
QIcon ic = QIcon(qvariant_cast<QPixmap>(index.data(Qt::DecorationRole)));
QTextDocument doc;
QString txt = index.data(Qt::DisplayRole).toString();
doc.setHtml(txt);
// rectangle for the icon
QRect r = option.rect.adjusted(2, 2, -2, -2);
ic.paint(painter, r, Qt::AlignVCenter|Qt::AlignLeft);
// rectangle for the text
r = r.adjusted(60, 0, 0, 0);
doc.drawContents(painter, r);
painter->restore();
}
Any suggestions?
Thx Luke
I try to create my own delegate for a list view.
I'd like to draw my list items similar to the default behaviour. That is a picture on the left side and than a text. But the text is in html format to support some formation as different text size and text colour.
So I implemented my ouwn QStyledItemDelegate::paint method. But my items are not painted properly.
The first item is painted as supposed. But for the other items only the image is painted.
When I scroll the list view then sometimes other items are painted. But the text is drawn to far left and under the images.
void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
if(!index.isValid())
return;
painter->save();
// handle selection
if(option.state & QStyle::State_Selected){
painter->fillRect(option.rect, option.palette.color(QPalette::Highlight));
}
// get the oicture for the decoration role
QIcon ic = QIcon(qvariant_cast<QPixmap>(index.data(Qt::DecorationRole)));
QTextDocument doc;
QString txt = index.data(Qt::DisplayRole).toString();
doc.setHtml(txt);
// rectangle for the icon
QRect r = option.rect.adjusted(2, 2, -2, -2);
ic.paint(painter, r, Qt::AlignVCenter|Qt::AlignLeft);
// rectangle for the text
r = r.adjusted(60, 0, 0, 0);
doc.drawContents(painter, r);
painter->restore();
}
Any suggestions?
Thx Luke