Skip to content
Advertisement

QTextedit find() always returns False (pyside2)

I want to do some search and replace in a QTextEdit but QTextEdit.find() always returns False/finds nothing. Where is my mistake?

Here is a (very) minimal reproducible example:

from PySide2.QtWidgets import QApplication, QTextEdit
from PySide2.QtGui import QTextCursor
import sys

app = QApplication(sys.argv)
textedit = QTextEdit()
cursor = textedit.textCursor()
cursor.insertText("test test test")
cursor.movePosition(QTextCursor.Start)
print(textedit.find("t"))
textedit.show()
app.exec_()

Thx for that -.-: “This question already has an answer here: QTextEdit.find() doesn’t work in Python”

That is not true. (Maybe read the questions and answers before stating something like that and closing questions. This is the behavior why stackoverflow has such a bad reputation.): “The problem is the position of the cursor in the window. By default the search only happens forward (= from the position of the cursor onwards). But i set my cursor to the start of the document via cursor.movePosition(QTextCursor.Start)

Advertisement

Answer

I found that textedit.textCursor() creates local copy of position and it doesn’t change original position in QTextEdit.

You have to update position in QTextEdit using

textedit.setTextCursor(cursor) 

and then find() will find first t as you expect.


from PySide2.QtWidgets import QApplication, QTextEdit
from PySide2.QtGui import QTextCursor
import sys

app = QApplication(sys.argv)

textedit = QTextEdit()

cursor = textedit.textCursor()   # get local copy
cursor.insertText("test test test")
cursor.movePosition(QTextCursor.Start)
textedit.setTextCursor(cursor)   # update it

#textedit.insertPlainText("test test test")
#textedit.moveCursor(QTextCursor.Start)

textedit.show()

print(textedit.find("t"))  # first `t`
print(textedit.find("t"))  # second `t`

app.exec_()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement