在 QTreeView (Qt/PySide/PyQt) 中实现自动换行的委托?

eri*_*ric 2 qt pyqt pyqt4 pyside

我有一个带有自定义委托的树视图,我正在尝试向其中添加自动换行功能。自动换行工作正常,但sizeHint()似乎不起作用,因此当文本换行时,相关行不会扩展以包含它。

我以为我sizeHint()回来照顾它document.size().height()

def sizeHint(self, option, index):
    text = index.model().data(index)
    document = QtGui.QTextDocument()
    document.setHtml(text) 
    document.setTextWidth(option.rect.width())  
    return QtCore.QSize(document.idealWidth(), document.size().height())    
Run Code Online (Sandbox Code Playgroud)

但是,当我打印出来document.size().height()时,每个项目都是一样的。

此外,即使我手动设置高度(例如,设置为 75)只是为了检查事情看起来是否合理,树看起来就像是被火箭筒射中的金鱼(也就是说,它是一团糟):

跆拳道

如您所见,每行中的文本在树中没有正确对齐。

类似帖子

之前也出现过类似的问题,但是没有解决我的问题(人们通常说要重新实现 sizeHint(),这就是我正在尝试的):

QTreeWidget 根据内容设置每行的高度

QTreeView 自定义各行的行高

http://www.qtcentre.org/threads/1289-QT4-QTreeView-and-rows-with-multiple-lines

南昌

def sizeHint(self, option, index):
    text = index.model().data(index)
    document = QtGui.QTextDocument()
    document.setHtml(text) 
    document.setTextWidth(option.rect.width())  
    return QtCore.QSize(document.idealWidth(), document.size().height())    
Run Code Online (Sandbox Code Playgroud)

thr*_*les 5

这个问题似乎源于这样一个事实,即option.rect.width()传入的值QStyledItemDelegate.sizeHint()是 -1。这明显是假的!

我通过在paint()方法中存储模型中的宽度并从sizeHint().

因此,在您的paint()方法中添加以下行:

index.model().setData(index, option.rect.width(), QtCore.Qt.UserRole+1)
Run Code Online (Sandbox Code Playgroud)

并在您的sizeHint()方法中,替换document.setTextWidth(option.rect.width())为:

width = index.model().data(index, QtCore.Qt.UserRole+1)
if not width:
    width = 20
document.setTextWidth(width)
Run Code Online (Sandbox Code Playgroud)