PDA

View Full Version : Custom Delegate and Text Wrap



enlightened_j
17th September 2010, 02:38
Hi,

I have a custom delegate that draws text and an image right beneath the text for each item in a QStandardItemModel like the attached screenshot. 5199

As you can see, the text is covered by the image once it wraps because image location is fixed for each item. I could not figure out a way to query for the Y position of the text that will be painted after calling drawText() and set my image location accordingly. Google search and browse through this forum does not reveal any hint, please suggest how I could accomplish it.

I have attached a simplified version of code to reproduce the behavior and thanks in advance for any reply!!
5198
The current paint code looks like:


void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QApplication::style()->drawPrimitive( QStyle::PE_PanelItemViewItem, &option, painter );
painter->save();
painter->translate(option.rect.topLeft());

const QRect line(0, 0, option.rect.width(), option.rect.height());
painter->setClipRect(line);

if(option.state & QStyle::State_Selected) {
painter->fillRect(option.rect, option.palette.color(QPalette::Highlight));
}

QString txt = index.data(Qt::DisplayRole).toString();
QRect r = QRect(PADDING, 0, option.rect.width() - PADDING, option.rect.height() - PADDING);
r = painter->boundingRect(r, Qt::AlignLeft | Qt::AlignTop | Qt::TextWordWrap, txt);
painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeft|Qt::TextWordWrap, txt);

QImage ic = QImage(qvariant_cast<QImage>(index.data(Qt::DecorationRole)));
r = QRect(0, PADDING*2, PIC_WIDTH, PIC_HEIGHT);
painter->drawImage(r, ic);
painter->restore();
}

ChrisW67
17th September 2010, 03:25
The QPainter::boundingRect() return value should tell you the actual size of the rectangle that the text will occupy. So the r.height() value should give you an idea where to put the top edge of the image.

Lykurg
17th September 2010, 06:21
...or you can use QFontMetrics::boundingRect(). Get it via option.fontMetrics.