Fun with PyQt — Setting alignment of all paragraphs in a QTextEdit

Hey, kids! You wanna center-align all the text in a Text Edit input?

You might have noticed that QTextEdit.setAlignment() only applies the new alignment to the current paragraph. You may also have noticed there’s no handy method for iterating through paragraphs. You may also have noticed that, if you use the nice QTextCursor.movePosition() method that returns a boolean to let you know when you’re done, it doesn’t actually move the text edit’s cursor — but if you use QTextEdit.moveCursor(), it doesn’t return a boolean. Oops.

Here’s what I did:

   def setAlignment(self, textEdit, desiredAlignment):

   #Make sure the cursor is at the start of the text field


   lastPosition = -1
   currPosition = textEdit.textCursor().position()
   while lastPosition != currPosition :
      lastPosition = currPosition
      currPosition = textEdit.textCursor().position()

    #Move to the end of the text field in preparation for whatever comes next




Draws. Sweats. Eats too much sugar-free candy.

You may also like...

2 Responses

  1. Tory says:

    OK — try this instead of the last “moveCursor()” call:

    #Move the cursor to where we were
    #(Note “setPosition()” doesn’t actually move the cursor. WEAK.)
    while textEdit.textCursor().position() < whereWeWere : textEdit.moveCursor(QTextCursor.MoveOperation(QTextCursor.Right))

  2. Tory says:

    Uh — I’m revisiting this issue as there is a bug in this code. It boots you to the end of the textEdit no matter where you were editing. NOT COOL. Mah bad.

%d bloggers like this: