【问题标题】:Draw adjustable text in QTableView cell在 QTableView 单元格中绘制可调整的文本
【发布时间】:2015-02-06 13:51:21
【问题描述】:

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

elif index.column() == 3:
    title = index.data()
    painter.drawText(option.rect, QtCore.Qt.AlignCenter, title)

但是当我尝试这样显示时,我遇到了一个小问题。

预期:

现实:

要获得预期的图片,我只需要在 StyledItemDelegate 中的此列上什么都不做。我需要做同样的事情,但使用函数 drawText。

你有什么想法吗?

【问题讨论】:

  • 我不熟悉这个工具包,所以不敢回答。但我猜你需要设置wordWrap

标签: python pyqt qstyleditemdelegate


【解决方案1】:

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

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

这个 sn-p 基本上是为那些想要通过 QStyledItemDelegate 即时修改内容和/或内容格式的人准备的:

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()

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-05-20
  • 2023-03-13
  • 2021-07-30
  • 1970-01-01
  • 2014-02-27
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
相关资源
最近更新 更多