在 QTableView 单元格中绘制可调整的文本

Draw adjustable text in QTableView cell

我需要子class 我的 QTableView 的 QStyledItemDelegate。更具体地说,我需要修改特定列的显示。此列中的单元格通常包含文本。这是我的自定义 QStyledItemDelegate class:

的一小部分
elif index.column() == 3:
    title = index.data()
    painter.drawText(option.rect, QtCore.Qt.AlignCenter, title)

但是我有一个小问题,当我尝试像这样显示它时。

预计:

现实:

要获得预期的图片,我只需要在 StyledItemDelegate 中的这一列上不执行任何操作。我需要做同样的事情,但使用函数 drawText。

你有什么想法吗?

好的,我在这里找到了答案:Word Wrap with HTML? QTabelView and Delegates

它还将文本转换为 html 并允许 html 格式化(我也需要它),但我认为它可以很容易地转换为显示简单文本,并自动换行。

此代码段基本上适用于那些想要通过 QStyledItemDelegate 即时修改内容 and/or 内容格式的人:

options = QtGui.QStyleOptionViewItemV4(option)
self.initStyleOption(options, index)

painter.save()

doc = QtGui.QTextDocument()
text_option = QtGui.QTextOption(doc.defaultTextOption())
text_option.setWrapMode(QtGui.QTextOption.WordWrap)
doc.setDefaultTextOption(text_option)

# Modify the text here. Ex:
# options.text += "<br><br>"
doc.setHtml(options.text)
doc.setTextWidth(options.rect.width())

options.text = ""
options.widget.style().drawControl(QtGui.QStyle.CE_ItemViewItem, options, painter)

# Center the text vertically
height = int(doc.documentLayout().documentSize().height())
painter.translate(options.rect.left(), options.rect.top() + options.rect.height() / 2 - height / 2)

clip = QtCore.QRectF(0, 0, options.rect.width(), options.rect.height())
 doc.drawContents(painter, clip)

painter.restore()