【问题标题】:How to get QTreeView cell width inside QItemDelegate sizeHint()?如何在 QItemDelegate sizeHint() 中获取 QTreeView 单元格宽度?
【发布时间】:2012-02-14 12:28:54
【问题描述】:

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

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

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

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

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

【问题讨论】:

    标签: python qt pyqt paint qitemdelegate


    【解决方案1】:

    原文:我使用基类的 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);
    

    【讨论】:

    • 基本 sizeHint 不是单元格宽度。它是单元格内数据的大小。但由于我自己绘制所有数据,因此基本 sizeHint 认为单元格没有数据并返回超小宽度。
    • 完美解决方案。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 2015-11-08
    • 2020-11-19
    • 1970-01-01
    相关资源
    最近更新 更多