Issue
I'm trying to select different text in a QTextEdit object.
def get_text_cursor(self):
return self.TextEdit.textCursor()
def get_text_selection(self):
cursor = self.get_text_cursor()
return cursor.selectionStart(), cursor.selectionEnd()
def set_text_selection(self, start, end):
cursor = self.get_text_cursor()
cursor.setPosition(start, end)
self.TextEdit.setTextCursor(cursor)
This code does NOT work (get_text_selection
does work) I have tried other things as well and they don't work either.
This question was already asked (but not really answered) here Select text of textEdit object with QTextCursor, QTextEdit
Working code, thanks to ekhumoro
# text cursor functions
def get_text_cursor(self):
return self.TextEdit.textCursor()
def set_text_cursor_pos(self, value):
tc = self.get_text_cursor()
tc.setPosition(value, QtGui.QTextCursor.KeepAnchor)
self.TextEdit.setTextCursor(tc)
def get_text_cursor_pos(self):
return self.get_text_cursor().position()
def get_text_selection(self):
cursor = self.get_text_cursor()
return cursor.selectionStart(), cursor.selectionEnd()
def set_text_selection(self, start, end):
cursor = self.get_text_cursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
self.TextEdit.setTextCursor(cursor)
You can see this code in action at https://github.com/cloudformdesign/SearchTheSky
Solution
For QTextEdit, the selection is demarcated by the current postion and the anchor. But confusingly, although QTextCursor has a setPostion
method for setting the current position, there is no corresponding setAnchor
method for setting the anchor. So you have to call setPostion
twice with a special flag:
cursor = self.edit.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
self.TextEdit.setTextCursor(cursor)
Answered By - ekhumoro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.