原文:我使用基类的 sizeHint() 方法来获取单元格大小,然后根据需要修改 QSize,如下所示:
QSize MyDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QSize sz=QItemDelegate::sizeHint(option, index);
int h=sz.height();
< MODIFY h HERE >
sz.setHeight(h);
return sz;
}
似乎工作正常。
编辑:海报表明这对他不起作用......所以这是另一个选择,也许不是最优雅的:向代表添加一个视图成员(我想不出从代表那里得到的方法),并使用模型索引来获取标题的部分大小。例如:
class MyDelegate : public QItemDelegate
{
public:
<the usual, then add>
void setView(QAbstractItemView* v) { theView=v; }
protected:
QAbstractItemView* theView;
};
并在实施中
QSize MyDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
int theWidth=-1;
// handle other types of view here if needed
QTreeView* tree=qobject_cast<QTreeView*>(theView);
if(tree)
{
qDebug("WIDTH @ %d : %d",index.column(),tree->header()->sectionSize(index.column()));
theWidth=tree->header()->sectionSize(index.column());
}
QSize sz=QItemDelegate::sizeHint(option, index);
if(theWidth>=0)
sz.setWidth(theWidth);
// compute height here and call sz.setHeight()
return sz;
}
剩下要做的就是在您的代码中,在创建委托后,调用 setView():
MyDelegate* theDelegate=new MyDelegate(...);
theDelegate->setView(theView);