QTreeView custom row height of individual rows

2019-09-11 03:35发布

问题:

Is it possible to redefine the row height of certain individual rows within a QTreeView?

I have a custom QTreeView, custom QAbstractItemModel and a custom QStyledItemDelegate, but it seems that all the sizeHint methods are either called only once (initially) or are not virtual in the base classes.

Qt Version 4.7.4, no upgrade to 5 possible.

Any help appreciated.

回答1:

Reimplement the delegate’s sizeHint(). Found an example in some production code of mine. It is shown simplified below. In the example, the tree may contain images. Therefore the cell sizes need to be adjusted to host the images.

class ItemDelegate : public QItemDelegate
{
  public:
      QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
      {
           const TreeItem* ti(static_cast<TreeItem*>(index.internalPointer()));
           if(ti->pixmap())
              return ti->pixmap()->size();
           QItemDelegate::sizeHint(option,index);
      }
};

Usage:

 QTreeView view;
 ItemDelegate *delegate = new ItemDelegate;
 view.setItemDelegate(delegate);


标签: qt qt4 qt5