Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Unable to center align all text in QTextEdit box (multi line strings).



  • Hi there,

    I've been trying out multiple solutions on how to center each line appended to a text edit box, but none have worked for me so far. I have read that each line in the text edit box has to have its alignment set.

    A few of the solutions I've tried:
    https://forum.qt.io/topic/93185/qtextedit-alignment-doesn-t-work/3
    https://stackoverflow.com/questions/25855024/aligning-text-in-qtextedit
    https://forum.qt.io/topic/87456/how-to-align-text-in-qtextedit

    I have created a custom error message window in Qt Designer and created a text edit box which I named "txt_message". My intention is to pass my "errow_window.py"'s update method a multi line string ("""formated with tripple quotes"""). Here's my current code:

    def update(self, title, message):
        self.txt_message.clear()
        self.setWindowTitle(title)
    
        lines = message.splitlines()
    
        for line in lines:
            self.txt_message.append(line)
            self.center_paragraph_text()
    
    def center_paragraph_text(self):
        cursor = self.txt_message.textCursor()
        block_format = cursor.blockFormat()
        block_format.setAlignment(Qt.AlignCenter)
        cursor.mergeBlockFormat(block_format)
        self.txt_message.setTextCursor(cursor)
    

    At the moment it currently centers the very first line appended to the text exit box. But after the first line, the following lines all seem to be right aligned. Example formatting:
    ExampleFormatting.PNG

    How can I get each new line of text be centered like the first line? I would appreciate any help on this, I'm stumped.



  • It took me a whole day, but I finally figured it out. When you use a multi line string it adds extra tab indentation to every line after the first. I found that python has a standard library called "inspect" which has a nifty method called "cleandoc". This can be used to remove the extra indentation automatically added (which you never expected to have in the first place).

    While I was at it, I also found an easier way to center align the text than I was using before. Here is the updated and working code:

    import inspect
    
    def update(self, title, message):
        self.txt_message.clear()
        self.setWindowTitle(title)
    
        message = inspect.cleandoc(message)
        lines = message.splitlines()
    
        for line in lines:
            self.txt_message.append(line)
            self.txt_message.setAlignment(Qt.AlignCenter)
    

    I hope this saves others the headache I got from exploring all the numerous forum posts on this subject. Cheers!


Log in to reply