如题, 想改变QTreeView中每个节点的行高度, 在查询Qt参考文档没有得到结果后, 转到网上查询, 得到两种方法, 摘录如下:
1. 继承QItemDelegate类, 并重载其中的sizeHint函数, 在sizeHint函数中实现给定行高, 将该继承类的对象通过QTreeView::setItemDelegate方法指定给treeview对象;
这个方法经过实际试验是可行的, 我的Delegate类的sizeHint方法如下:
/// \reimp
QSize MyDelegate::sizeHint ( const QStyleOptionViewItem & option,
const QModelIndex & index ) const
{
QSize size = QItemDelegate::sizeHint(option, index);
size.setHeight( size.height() + 4 );
return size;
}2. 第二个方法是在ItemModel的data方法中, 实现当role==Qt::SizeHintRole时, 返回一个特定的QSize对象, 即可实现自定义行高的效果; 如 (这个方法未经实际的程序检验, 仅供参考)
// 重载QAbstractItemModel方法
QVariant MyModel::data ( const QModelIndex & index, int role ) const
{
switch(role)
{
case Qt::SizeHintRole:
// 返回单元格尺寸
return QSize(16, 35);
break;
case Qt::TextAlignmentRole:
......
}
}
本文介绍了如何在Qt的QTreeView中设置行高,提供了两种方法:一是通过继承QItemDelegate并重写sizeHint函数,二是通过在ItemModel的data方法中处理Qt::SizeHintRole。第一种方法已验证可行,第二种方法未实际测试。
447





