我在上一个答案中所做的计算是不正确的,因为返回的大小
sizeHint()
是相对于上一项的。一个简单的解决方案是使用
Qt::SizeHintRole
import os
from PyQt5 import QtCore, QtGui, QtWidgets, uic
class HTMLDelegate(QtWidgets.QStyledItemDelegate):
def __init__(self, parent=None):
super(HTMLDelegate, self).__init__(parent)
self.doc = QtGui.QTextDocument(self)
def paint(self, painter, option, index):
painter.save()
options = QtWidgets.QStyleOptionViewItem(option)
self.initStyleOption(options, index)
self.doc.setHtml(options.text)
options.text = ""
style = QApplication.style() if options.widget is None \
else options.widget.style()
style.drawControl(QtWidgets.QStyle.CE_ItemViewItem, options, painter)
ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
if option.state & QtWidgets.QStyle.State_Selected:
ctx.palette.setColor(QtGui.QPalette.Text, option.palette.color(
QtGui.QPalette.Active, QtGui.QPalette.HighlightedText))
else:
ctx.palette.setColor(QtGui.QPalette.Text, option.palette.color(
QtGui.QPalette.Active, QtGui.QPalette.Text))
textRect = style.subElementRect(QtWidgets.QStyle.SE_ItemViewItemText, options, None)
if index.column() != 0:
textRect.adjust(5, 0, 0, 0)
constant = 4
margin = (option.rect.height() - options.fontMetrics.height()) // 2
margin = margin - constant
textRect.setTop(textRect.top() + margin)
painter.translate(textRect.topLeft())
painter.setClipRect(textRect.translated(-textRect.topLeft()))
self.doc.documentLayout().draw(painter, ctx)
painter.restore()
s = QtCore.QSize(self.doc.idealWidth(), self.doc.size().height())
index.model().setData(index, s, QtCore.Qt.SizeHintRole)
class GUI(QtWidgets.QDialog):
def __init__(self):
super(GUI, self).__init__()
dirname = os.path.dirname(os.path.abspath(__file__))
uic.loadUi(os.path.join(dirname,'main.ui'), self)
delegate = HTMLDelegate(self.lwOptions)
self.lwOptions.setItemDelegate(delegate)
for ordinal in ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth']:
item = QtWidgets.QListWidgetItem('This is the <b>{}</b> word. This is the <b>{}</b> word. This is the <b>{}</b> word.'.format(ordinal, ordinal, ordinal))
self.lwOptions.addItem(item)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = GUI()
window.show()
sys.exit(app.exec_())