使用代理(PySide/Qt/PyQt)垂直居中项目文本

3
我有一个自定义的委托用于QTableView,允许使用QTextDocument显示/编辑HTML字符串。下面是一个SSCCE。

不幸的是,当我使用paint()显示文本时,它并没有垂直居中,而是似乎顶部对齐。例如,如果我将该委托应用于第二列,但不是第一列,则表格如下所示:

the problem

我的搜索并没有揭示如何从委托内部以原则性的方式修复此问题。在我的电脑上手动添加5到option.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()
1个回答

5

您应该使用QTextDocument::setTextWidth来设置文档的宽度。这将允许您确定文本高度并将其用于计算偏移量:

document.setTextWidth(option.rect.width())
offset_y = (option.rect.height() - document.size().height())/2
painter.translate(option.rect.x(), option.rect.y() + offset_y) 
document.drawContents(painter) 

设置文本宽度也很必要,否则当列宽不足时文本就不会换行。

你可能需要重新实现sizeHint方法,基于文档大小计算首选宽度和高度。


哇!是的,我有一个实现了 sizeHint 的完整示例。我只想将我的SSCCE简化到基本点。既然这个问题看起来已经解决了,我得检查一下看我做对了没有。 :) - eric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接