はんぎょねこの憂鬱

耳から変な汁が出てきた

QTreeWidgetItemでアイコン複数表示

HTMLを表示するdelegateを用意するのが手っ取り早い

f:id:dungeonneko:20170411134501p:plain

コードはここらへんを参考に

stackoverflow.com

PyQt版の回答をゴニョゴニョして作成

import sys
from PySide import QtCore, QtGui


class RichTextDelegate(QtGui.QStyledItemDelegate):
    def paint(self, painter, option, index):
        option_v4 = QtGui.QStyleOptionViewItemV4(option)
        self.initStyleOption(option_v4, index)
        doc = self.make_text(option_v4.text)

        option_v4.text = ""
        style = QtGui.QApplication.style()
        style.drawControl(QtGui.QStyle.CE_ItemViewItem, option_v4, painter)

        painter.save()
        rect = style.subElementRect(QtGui.QStyle.SE_ItemViewItemText, option_v4)
        painter.translate(rect.topLeft())
        painter.setClipRect(rect.translated(-rect.topLeft()))
        context = QtGui.QAbstractTextDocumentLayout.PaintContext()
        if option_v4.state & QtGui.QStyle.State_Selected:
            context.palette.setColor(
                QtGui.QPalette.Text, option.palette.color(QtGui.QPalette.Active, QtGui.QPalette.HighlightedText))
        doc.documentLayout().draw(painter, context)
        painter.restore()

    def sizeHint(self, option, index):
        option_v4 = QtGui.QStyleOptionViewItemV4(option)
        self.initStyleOption(option_v4, index)
        doc = self.make_text(option_v4.text)
        return QtCore.QSize(doc.idealWidth(), doc.size().height())

    def make_text(self, text):
        doc = QtGui.QTextDocument()
        doc.setDocumentMargin(1)
        f = QtGui.QTreeWidgetItem().font(0)
        f.setPointSize(11)
        doc.setDefaultFont(f)
        doc.setHtml(text)
        return doc


app = QtGui.QApplication(sys.argv)
tree = QtGui.QTreeWidget()
tree.setHeaderHidden(True)
tree.setItemDelegate(RichTextDelegate())
hoge = QtGui.QTreeWidgetItem()
hoge.setText(0, '<i>hoge</i> <img src="hoge.png"/><img src="hoge.png"/>')
fuga = QtGui.QTreeWidgetItem()
fuga.setText(0, '<b>fuga</b> <img src="hoge.png"/><img src="hoge.png"/><img src="hoge.png"/>')
piyo = QtGui.QTreeWidgetItem()
piyo.setText(0, '<font color="red">piyo</font>')
hoge.addChild(fuga)
hoge.addChild(piyo)
tree.addTopLevelItem(hoge)
tree.show()
sys.exit(app.exec_())