Search code examples
pythonqtformatqtextedit

Aligning text using format in a QTextEdit in Python


I want to display text in a QTextEdit. I use the format() function to align the text and make it look like a clean table. Although I get a perfect result when displaying the text in the shell, the text doesn't seem to align in the QTextEdit, like if the width of a character varies. I mainly see the difference when the character "-" is present.

>>> first_line = "{:<10} {:<3} - {:<20}".format("1234", "EUR", "Mrs Smith")
>>> second_line = "{:<10} {:<3} - {:<20}".format("-45.62", "GBP", "M Doe")
>>> print first_line, "\n", second_line
1234       EUR - Mrs Smith
-45.62     GBP - M Doe

The result as expected in the shell. But with the QTextEdit, the alignment is not right as you can see the slight difference between "EUR" and "GBP". It's not much in this example but when I use it with many more lines, it really doesn't look right.

my_text_edit = QTextEdit()
my_text_edit.append(first_line)
my_text_edit.append(second_line)

the alignment of the text is not right in this QTextEdit

I tried to use a QPlainTextEdit and got the same result. Anyway to get what I want with a QTextEdit/QPlainTextEdit ? or should I use another display widget (no editing is recquired, a label would do but I like the look of the text edit) ?


Solution

  • I was using the default font that doesn't have a fixed width, hence the non alignment. Setting the font to a fixed width font like 'monospace' solved my problem :

    fixed_font = QFont("monospace")
    fixed_font.setStyleHint(QFont.TypeWriter)
    my_text_edit.setFont(fixed_font)
    

    I used "setStyleHint" to indicate which kind of font Qt should use if 'monospace' is not found on the system, "QFont.TypeWriter" indicating to choose a fixed pitch font so the alignment is still respected.