I have implemented a "replace all" function that gets triggered when the replace all button on the "Find and replace" window is pressed. However, if I try to undo the changes with the build-in undo function nothing happens.
Does it have something to do with my text editor not being focused when the dialog window shows?
def handle_replace_all():
old = find_win.line_edit_find.text() # text to replace
new = find_win.line_edit_replace.text() # new text
cursor = self.text_edit.textCursor()
cursor.beginEditBlock()
current_text = self.text_edit.toPlainText()
replaced_text = current_text.replace(old, new)
self.text_edit.setPlainText(replaced_text)
cursor.endEditBlock()
find_window.button_replace_all.clicked.connect(handle_replace_all)
Why is that happening? Appreciate any help.
If you want to use the undo-redo functionality you must make the modifications using only the QTextCursor
:
def handle_replace_all(self):
old = find_win.line_edit_find.text() # text to replace
new = find_win.line_edit_replace.text() # new text
current_text = self.text_edit.toPlainText()
replaced_text = current_text.replace(old, new)
cursor = self.text_edit.textCursor()
cursor.beginEditBlock()
cursor.select(QtGui.QTextCursor.Document)
cursor.removeSelectedText()
cursor.insertText(replaced_text)
cursor.endEditBlock()