Warning: Use of undefined constant headerfavicons - assumed 'headerfavicons' (this will throw an Error in a future version of PHP) in /home/thetoryp/www/www/wp-content/plugins/easy-favicon/easy-favicon.php on line 6231

Warning: Use of undefined constant headerfavicons - assumed 'headerfavicons' (this will throw an Error in a future version of PHP) in /home/thetoryp/www/www/wp-content/plugins/easy-favicon/easy-favicon.php on line 6279

Warning: Use of undefined constant headerfavicons - assumed 'headerfavicons' (this will throw an Error in a future version of PHP) in /home/thetoryp/www/www/wp-content/plugins/easy-favicon/easy-favicon.php on line 6327
Fun with PyQt - Setting alignment of all paragraphs in a QTextEdit - Programming - The Tory Party Skip to content

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

Fun with PyQt — Setting alignment of all paragraphs in a QTextEdit published on 2 Comments on 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
   #

   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!

(1,132 visits, 2 today)

2 Comments

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.)
#
textEdit.moveCursor(QTextCursor.Start)
while textEdit.textCursor().position() < whereWeWere : textEdit.moveCursor(QTextCursor.MoveOperation(QTextCursor.Right))

Primary Sidebar