5 python qt pyqt paint qitemdelegate
我在QTreeView中有一个自定义QItemDelegate绘图文本.在paint()中,我从样式中获取单元格的大小.然后我使用wordwrap使用当前单元格的宽度绘制文本.
在sizeHint()中,我真的只想计算高度.宽度应该是当前单元格宽度.当用户更改单元格宽度时,sizeHint将只计算单词包装文本的新高度并返回该高度.
问题是我无法像在paint()中那样获取sizeHint()中的单元格宽度.我用的是:
style = QApplication.style()
style.subElementRect(QStyle.SE_ItemViewItemText, option).width()
Run Code Online (Sandbox Code Playgroud)
这适用于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;
}
Run Code Online (Sandbox Code Playgroud)
似乎工作正常.
编辑:海报表明这对他不起作用......所以这是另一种选择,也许不是最优雅的:将一个视图成员添加到委托中(我想不出从委托中获取的方式),并使用模型索引来获取标题的节大小.例如:
class MyDelegate : public QItemDelegate
{
public:
<the usual, then add>
void setView(QAbstractItemView* v) { theView=v; }
protected:
QAbstractItemView* theView;
};
Run Code Online (Sandbox Code Playgroud)
并在实施中
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;
}
Run Code Online (Sandbox Code Playgroud)
只剩下要做的就是在代码中创建委托后,调用setView():
MyDelegate* theDelegate=new MyDelegate(...);
theDelegate->setView(theView);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2718 次 |
| 最近记录: |