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:
Valid alignments are Qt.AlignLeft, Qt.AlignRight, Qt.AlignJustify and Qt.AlignCenter (which centers horizontally).
That is, there is no native support for vertical alignment. Is there an indirect way to vertically center the text in QTextEdit
?
Related link
Center the Text of QTextEdit horizontally and vertically : Unfortunately, the accepted answer uses QLineEdit
which won't work for me.
A clue?
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.
Using the example delegate from your previous question, it can be achieved like this:
(NB: the reimplemented
sizeHint
andminimumSizeHint
methods are probably redundant in the original example).While the accepted answer works for default font size, it breaks when I change the font size or vertical margins (see comments). The text line edit class below centers the text vertically, for all font sizes and vertical margins that I've tested.
It sets up the editor using
QTextDocument
which is then assigned to theQTextEdit
instance.QTextDocument
s provide the back-end containers forQTextEdit
s anyway, and have built-in functionality for handling font sizes and margins, and give an additional layer of control over the editor.In practice, I found using
QTextDocument
let me solve the problem in a more intuitive way without having, you don't have to delve into the nitty-gritty mechanics of frame widths, font metrics, and all that, which we did when working solely using nativeQTextEdit
methods.Note it uses
setViewportMargins()
instead ofsetContentMargins()
(which is what you might expect it to use) because the latter is for setting margins for something that is inserted into a layout. The following editor is a standalone widget, not put into any layout, sosetContentMargins()
won't do anything.