gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:03:24 27 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

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

似乎工作正常。

编辑:发帖者表示这对他不起作用...所以这里有另一个选项,也许不是最优雅的:向委托(delegate)添加一个 View 成员(我想不到一种从委托(delegate)中获取的方法),并使用模型索引来获取 header 的部分大小。例如:

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;
}

唯一剩下要做的就是在您的代码中,在创建委托(delegate)后调用 setView():

MyDelegate* theDelegate=new MyDelegate(...);
theDelegate->setView(theView);

关于python - 如何在 QItemDelegate sizeHint() 中获取 QTreeView 单元格宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8932966/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com