Skip to content Skip to sidebar Skip to footer

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 i

Solution 1:

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.

Solution 2:

I got good results with aligning text or floats by using Unicode spacing, with python format.

Example:

self.mlist.append('{:\u2000<11d}'.format(martnr)+\
    '{:\u2000<40s}'.format(momschr)+'\n'+\
    '{:\u2000>6d}'.format(int(maantal))+\
    '{:\u2000>12.2f}'.format(mprijs)+\
    '{:\u2000>12.2f}'.format(float(mprijs)*float(maantal))+\
    '{:\u2000>12.2f}'.format(float(mprijs)*float(maantal)*mbtw))

self.view.append(self.mlist[-1])

Where self.view is a QTextEdit view

Post a Comment for "Aligning Text Using Format In A Qtextedit In Python"