我有一个自定义代表QTableView
允许显示/编辑 html 字符串(使用QTextDocument
)。下面有一个 SSCCE。
不幸的是,当我使用显示文本时paint()
,它不是垂直居中的,但似乎顶部对齐。例如,如果我将委托应用于第二列,而不是第一列,则表如下所示:
我的搜索没有揭示任何关于如何以原则性的方式从委托内部解决此问题的信息。手动添加 5option.rect.y()
在我的电脑上可以运行,但我不认为这是有原则的。
有没有办法让文字垂直居中?
SSCCE
from PySide import QtGui
import sys
class HtmlTable(QtGui.QTableView):
def __init__(self, parent = None):
QtGui.QTableView.__init__(self)
model = QtGui.QStandardItemModel()
model.setHorizontalHeaderLabels(['Title', 'Summary'])
item0 = [QtGui.QStandardItem('Infinite Jest'), QtGui.QStandardItem('Hello, <i>Hal</i>')]
item00 = [QtGui.QStandardItem('Hamlet'), QtGui.QStandardItem('Best served <b>cold</b>')]
model.appendRow(item0)
model.appendRow(item00)
self.setModel(model)
self.setItemDelegate(HtmlPainter(self))
class HtmlPainter(QtGui.QStyledItemDelegate):
def __init__(self, parent=None):
QtGui.QStyledItemDelegate.__init__(self, parent)
def paint(self, painter, option, index):
if index.column() == 1:
text = index.model().data(index) #default role is display
palette = QtGui.QApplication.palette()
document = QtGui.QTextDocument()
document.setDefaultFont(option.font)
#Set text (color depends on whether selected)
if option.state & QtGui.QStyle.State_Selected:
displayString = "<font color={0}>{1}</font>".format(palette.highlightedText().color().name(), text)
document.setHtml(displayString)
else:
document.setHtml(text)
#Set background color
bgColor = palette.highlight().color() if (option.state & QtGui.QStyle.State_Selected)\
else palette.base().color()
painter.save()
painter.fillRect(option.rect, bgColor)
painter.translate(option.rect.x(), option.rect.y()) #If I add +5 it works
document.drawContents(painter)
painter.restore()
else:
QtGui.QStyledItemDelegate.paint(self, painter, option, index)
def main():
app = QtGui.QApplication(sys.argv)
myTable = HtmlTable()
myTable.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()