如何在 QTextEdit 实例 (PySide/PyQt) 中垂直居中单行? [英] How to vertically center a single-line in a QTextEdit instance (PySide/PyQt)?

查看:171
本文介绍了如何在 QTextEdit 实例 (PySide/PyQt) 中垂直居中单行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从 QTextEdit 继承的行编辑器,我用它来编辑显示富文本的视图项.QTextEdit.setAlignment 的第二个参数是 `QtAligntment' 和 文档说:

I have a line editor that inherits from QTextEdit, and I am using it to edit view items that show rich text. The second parameter for QTextEdit.setAlignment is `QtAligntment' and the docs say:

有效对齐是 Qt.AlignLeft、Qt.AlignRight、Qt.AlignJustify 和Qt.AlignCenter(水平居中).

Valid alignments are Qt.AlignLeft, Qt.AlignRight, Qt.AlignJustify and Qt.AlignCenter (which centers horizontally).

也就是说,没有对垂直对齐的原生支持.在 QTextEdit 中是否有一种间接的方法可以将文本垂直居中?

That is, there is no native support for vertical alignment. Is there an indirect way to vertically center the text in QTextEdit?

相关链接

将 QTextEdit 的文本水平和垂直居中:不幸的是,接受的答案使用了 QLineEdit 这对我不起作用.

Center the Text of QTextEdit horizontally and vertically : Unfortunately, the accepted answer uses QLineEdit which won't work for me.

线索?

在下面我找到了一个关于如何在 C++/Qt 中做到这一点的线索.我几乎可以理解它,但不是完全,就像 C++ 一样:

At the following I found a clue about how to do it in C++/Qt. I am almost able to follow it, but not quite, as it is for c++:

http://www.qtcentre.org/threads/26003-Vertical-centering-of-a-QTextEdit

我将自己破解它几天并尝试自己回答它,但现在想发布这个以防有人已经破解它或以不同/更好的方式完成它.

I will hack at it on my own for a couple of days and try to answer it myself, but wanted to post this now in case someone has already cracked it already or done it in a different/better way.

推荐答案

对于垂直居中的单行编辑,您只需要计算一个正确的固定高度.

For a single-line edit centred vertically, you just need to calculate a correct fixed height.

使用您上一个问题中的示例委托,可以这样实现:

class RichTextLineEdit(QtGui.QTextEdit):   
    def __init__(self, parent=None):
        ...    
        margin = 1
        self.document().setDocumentMargin(margin)
        fontMetrics = QtGui.QFontMetrics(self.font())
        height = fontMetrics.height() + (margin + self.frameWidth()) * 2
        self.setFixedHeight(height)

(注意:重新实现的 sizeHintminimumSizeHint 方法在原始示例中可能是多余的).

(NB: the reimplemented sizeHint and minimumSizeHint methods are probably redundant in the original example).

这篇关于如何在 QTextEdit 实例 (PySide/PyQt) 中垂直居中单行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆