Tory Hoke

Essays, art, and comics of the unexpected

FOLLOW:

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

More

Most Recent Posts

Day 1: An Overview

(Experience this as a TikTok.) “Play is the work of childhood.” – Jean Piaget “or children, play is serious learning.” – Mr. Rogers Adult learning is

Read More »

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
   #

   textEdit.moveCursor(QtGui.QTextCursor.Start)

   lastPosition = -1
   currPosition = textEdit.textCursor().position()
   while lastPosition != currPosition :
      textEdit.setAlignment(desiredAlignment)
      textEdit.moveCursor(QtGui.QTextCursor.Down)
      lastPosition = currPosition
      currPosition = textEdit.textCursor().position()

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

   textEdit.moveCursor(QtGui.QTextCursor.End)

Woot!

Share This:

Comics: Rare Words

Comics: Sneaky VFX

Comics: Pure Silliness