Search code examples
pythonpyqtpyqt5alignmentqtextedit

How to center every line in a QTextEdit?


I'm using PyQt5.

I made a QTextEdit and I entered the code below:

self.descriptionText.setPlainText("First Line\nSecond Line\nThird Line")
self.descriptionText.setAlignment(Qt.AlignCenter)

But this is the result:

enter image description here

How can I center every line?


Solution

  • If you want every line to be centred, set the aligment first, and then insert the text:

    self.descriptionText.setAlignment(Qt.AlignCenter)
    self.descriptionText.insertPlainText("First Line\nSecond Line\nThird Line")
    

    The reason why your example doesn't work as expected, is because the setPlainText method clears the current aligment, and the setAlignment method only changes the alignment of the current paragraph. After you reset the text, the first paragraph will be the only one that's selected (because that's where the cursor is moved to), so the alignment will only get applied to the first line. Given this, another way of fixing your example would be:

    self.descriptionText.setPlainText("First Line\nSecond Line\nThird Line")
    self.descriptionText.selectAll()
    self.descriptionText.setAlignment(Qt.AlignCenter)