5

我在 QTreeView 中有一个自定义的 QItemDelegate 绘图文本。在paint() 中,我从样式中获取单元格的大小。然后我使用当前单元格的宽度绘制带有自动换行的文本。

在 sizeHint() 中,我真的只想计算高度。宽度应该是当前单元格宽度。当用户更改单元格宽度时,sizeHint 只会计算自动换行文本的新高度并将其返回。

问题是我无法像在paint() 中那样获得sizeHint() 内的单元格宽度。我正在使用:

style = QApplication.style()
style.subElementRect(QStyle.SE_ItemViewItemText, option).width()

这在paint() 中有效,但在sizeHint() 中返回-1。如何在 sizeHint() 中获取当前单元格宽度?

4

1 回答 1

6

原文:我使用基类的 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);
于 2012-01-19T23:56:04.043 回答