1

I'm writing a screenwriting application with PySide. What I want is to turn the characters to uppercase while the user is typing.

The following piece of code gives a runtime error saying "maximum recursion depth exceeded" every time I add a character. I get what it means and why it's happening but is there a different way?

self.cursor = self.recipient.textCursor()
self.cursor.movePosition(QTextCursor.StartOfLine)
self.cursor.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)
self.curtext = self.cursor.selectedText()
if len(self.curtext) > len(self.prevText):
    self.cursor.insertText(self.curtext.upper())
    self.cursor.clearSelection()
self.prevText = self.curtext

The code above runs whenever the text in the text edit widget is changed. The if statment prevents the code from running when the user hasn't insert text.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99

1 Answers1

3

You get a recursion error probably because when fixing the input to uppercase you are changing your content and again triggering the very same fixing routine. Also you constantly change the whole line while only a part has changed and needs to be fixed.

Fortunately Qt can do this itself using a QTextCharFormat. Here is the example that automatically keeps all text in a QLineEdit upper case. And you can do much more with it like underlining or making text bold...

Example:

from PySide import QtGui

app = QtGui.QApplication([])

widget = QtGui.QTextEdit()
fmt = QtGui.QTextCharFormat()
fmt.setFontCapitalization(QtGui.QFont.AllUppercase)
widget.setCurrentCharFormat(fmt)
widget.show()

app.exec_()
NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104