首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在QTreeView QItemDelegate sizeHint()中获取单元格宽度?

如何在QTreeView QItemDelegate sizeHint()中获取单元格宽度?
EN

Stack Overflow用户
提问于 2012-01-19 20:41:08
回答 1查看 3.3K关注 0票数 5

我在一个QItemDelegate中有一个自定义的QTreeView绘图文本。在the ()中,我从样式中得到单元格的大小。然后,我使用当前单元格的宽度,用字包装绘制文本。

在sizeHint()中,我只想计算高度。宽度应该只是当前单元格宽度的大小。当用户更改单元格宽度时,sizeHint将只计算单词包装文本的新高度并返回该高度。

问题是,我无法获得sizeHint()内部的单元格宽度,就像()中所做的那样。我用的是:

代码语言:javascript
复制
style = QApplication.style()
style.subElementRect(QStyle.SE_ItemViewItemText, option).width()

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

EN

回答 1

Stack Overflow用户

发布于 2012-01-19 23:56:04

原始:我使用基类‘sizeHint()方法来获得原来的单元格大小,然后根据需要修改QSize,如下所示:

代码语言:javascript
复制
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;
}

好像挺好的。

编辑:海报表明这不适用于他.因此,这里还有另一个选项,可能不是最优雅的:向委托中添加一个视图成员(我想不出从委托获取该成员的方法),并使用模型索引获取标头的节大小。例如:

代码语言:javascript
复制
class MyDelegate : public QItemDelegate
{
public:
    <the usual, then add>

    void setView(QAbstractItemView* v) { theView=v; }

protected:
    QAbstractItemView* theView;
};

以及在实施中

代码语言:javascript
复制
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():

代码语言:javascript
复制
MyDelegate* theDelegate=new MyDelegate(...);
theDelegate->setView(theView);
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8932966

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档