I am trying to select text programmatically using the QTextCursor in QPlainTextEdit. I am trying to create my selection by using the mouse[Press | Move | Release]Event.

Qt Code:
  1. def mousePressEvent(self, event):
  2. pos = event.pos()
  3. cursor = self.cursorForPosition(pos)
  4. self.start_pos = cursor.position()
  5. cursor.setPosition(self.start_pos,QTextCursor.MoveAnchor)
To copy to clipboard, switch view to plain text mode 

Qt Code:
  1. def mouseMoveEvent(self, event):
  2. pos = event.pos()
  3. cursor = self.cursorForPosition(pos)
  4. cursor.setPosition(cursor.position(),QTextCursor.KeepAnchor)
  5. print unicode(cursor.selectedText())
To copy to clipboard, switch view to plain text mode 

When I do this and try to select, it always prints an empty string.

I know by default that selections are already handled but I am trying to understand how to selections are done so that I can do some custom tasks. I have managed to get selections to work by using setPosition() followed by movePosition() but it would not highlight the selection. I determined that the selection was working by printing out the selected text.

My questions are, why doesn't my selection code for the mouse events work and second, when I do create a selection why doesn't it highlight the selection? Any help would be greatly appreciated.

Thanks,
Scott