我在一个QItemDelegate中有一个自定义的QTreeView绘图文本。在the ()中,我从样式中得到单元格的大小。然后,我使用当前单元格的宽度,用字包装绘制文本。
在sizeHint()中,我只想计算高度。宽度应该只是当前单元格宽度的大小。当用户更改单元格宽度时,sizeHint将只计算单词包装文本的新高度并返回该高度。
问题是,我无法获得sizeHint()内部的单元格宽度,就像()中所做的那样。我用的是:
style = QApplication.style()
style.subElementRect(QStyle.SE_ItemViewItemText, option).width()这在sizeHint()中有效,但在()中返回-1。如何在sizeHint()中获得当前单元格宽度?
发布于 2012-01-19 23:56:04
原始:我使用基类‘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);https://stackoverflow.com/questions/8932966
复制相似问题