Didac Perez Parera
Didac Perez Parera

Reputation: 3834

Varying list item size using delegate in Qt

I have a list view. That list view has items. For each item I use setItemDelegate and I override the paint method of the delegate. The think is that in each item I am writing some text, and when the text is really long there is no space enough.

How can I resize the item from the paint event? since I get the bounding box of the drawn text in the paint event.

Thanks in advance,

Upvotes: 3

Views: 1174

Answers (2)

andref
andref

Reputation: 4491

You cannot. When the item delegate's paint method is called, the list view has already been laid out and the QPainter you receive as argument might have a drawing surface that is the same size as the size hint or at least have a transform and clipping rect set to respect the size hint.

You must calculate the text size in the QAbstractItemDelegate::sizeHint method (using QFontMetrics) and return an appropriate size hint. Cache your results for better performance.

Upvotes: 2

Ruslan F.
Ruslan F.

Reputation: 5786

you need to implement sizeHint method

QListItemDelegat::QListItemDelegat(): QStyledItemDelegate(0){}
QSize

QListItemDelegat::sizeHint( const QStyleOptionViewItem& option, const DataClass& data ) const
{
   const QStyle* style( QApplication::style( ) );
   QFont nameFont( option.font );

   nameFont.setWeight( QFont::Bold );
   const QFontMetrics nameFM( nameFont );
   const QString nameStr( data.GetName() );
   int nameWidth = nameFM.width(nameStr);
   int nameHeight = nameFM.height(nameStr);
   return QSize(nameWidth ,nameHeight)
}

Upvotes: 1

Related Questions