I am using PyQt5. in QPlainTextEdit widget i want to move cursor to user defined position. but trying to set position of QTextCursor object through setPosition(new_position) value gives None. Having searched a couple of examples i havent been able to figure out whats the problem. Rest of the user interface is working fine.
I have a user interrface created with the help of Qt Designer. i am trying to make a find_replace dialog. first user entered word in a lineEdit ( lineEditFind) will be searched for in QPlainTextEdit widget using find method of QPlainTextEdit. upon finding the searched text QPlainTextEdit selects that found text and using insertText() method found text is replaced with another text provided by user through another lineEdit widget ( lineEditReplace) . It works fine. now I want the newly inserted text to be selected. so that user has clear idea of which word has been replaced.
self.ui.plainTextEdit.textCursor().insertText(str(self.dialog.lineEditReplace.text()))
# works fine after having replaced the text in above line I want to highlight the text
that was just replaced.
#cursor is right after the replaced text. So i want to move the cursor back and select the
replaced #text(word) using method QTextCursor.select(QTextCursor.WordUnderCursor)
pos=self.ui.plainTextEdit.textCursor().position() # gives correct
position after text replacement.
# however trying to set cursor position to one character back i.e. pos-1 doesnt work as
# setting position gives None instead of a QTextCursor object.
self.ui.plainTextEdit.textCursor().setPosition(pos-1)
# gives None instead of QTextCursor Object
I have tried a couple of ways but failed.
new_cursor=self.ui.plainTextEdit.textCursor() # make a new cursor object
new_cursor.setPosition(pos-1) # set position of new cursor object
self.ui.plainTextEdit.setTextCursor(new_cursor) # make new cursor the visible cursor
# gives error as new_cursor.setPosition(value) returns None