首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pyqt qstyleditemdelegate换行和html

pyqt qstyleditemdelegate换行和html
EN

Stack Overflow用户
提问于 2017-01-20 17:45:40
回答 1查看 607关注 0票数 2

网上的一个常见问题是如何在qlistview中使用qstyleditemdelegate来显示html。通常的答案是以下代码https://stackoverflow.com/a/5443112/2033030的变体

代码语言:javascript
复制
class HTMLDelegate(QtGui.QStyledItemDelegate):
    def paint(self, painter, option, index):
        options = QtGui.QStyleOptionViewItemV4(option)
        self.initStyleOption(options,index)

        style = QtGui.QApplication.style() if options.widget is None else options.widget.style()

        doc = QtGui.QTextDocument()
        doc.setHtml(options.text)

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

        ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
        if option.state & QStyle.State_Selected:
            ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText))
        else:
            ctx.palette.setColor(QPalette.Text, option.palette.color(QPalette.Active, QPalette.HighlightedText))


        textRect = style.subElementRect(QtGui.QStyle.SE_ItemViewItemText, options)
        painter.save()
        painter.translate(textRect.topLeft())
        painter.setClipRect(textRect.translated(-textRect.topLeft()))
        doc.documentLayout().draw(painter, ctx)

        painter.restore()

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

        doc = QtGui.QTextDocument()
        doc.setHtml(options.text)
        doc.setTextWidth(options.rect.width())
        return QtCore.QSize(doc.idealWidth(), doc.size().height())

这也是我在没有真正理解的情况下使用的。所以我的主要问题是如何启用自动换行功能?我尝试了很多方法,但都没有成功。

第二个问题是,有人能给我解释一下这段代码是做什么的吗,在我看来,它有点可疑。首先,它从原始的option参数创建一个optionS变量,但是下面的代码似乎随意使用了一个和另一个,所以我怀疑我们可以只使用option参数而不做任何更改。然后,它需要在paint和sizeHint中创建两次QTextDocument。然后在DrawControl中使用该样式,而不是在绘制QTextDocument时...

我确实把这两个问题都放在一个帖子里,所以我们希望我们能一起拿出一个有意义的示例代码,可以被许多人用作起点。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-15 03:14:58

解决方案是为TextDocument设置文本长度

代码语言:javascript
复制
doc.setTextWidth(options.rect.width())

但是这非常复杂,所以我们恢复使用QListWidgets,现在使用QML。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41760474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档