4

These are the widgets that I have,

self.recipient = QTextEdit(self)
self.document = QTextDocument(self)
self.recipient.setDocument(self.document)
self.cursor = QTextCursor(self.document)

and what I want to do is use the QTextCursor to copy the selected text in my QTextEdit. I have tried the function selectedText(), but it gives me an empty string. Here is how I try to print it:

print('%s' % (self.cursor.selectedText()))
NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104

1 Answers1

3

You need to retrieve the current cursor from the text-edit:

    cursor = self.recipient.textCursor()
    print('%s' % (cursor.selectedText()))

But note that this cursor is only a copy. If you make changes to it, those changes won't immediately update the text-edit. To do that, you need to reset the cursor, like this:

    # make some changes to the cursor
    cursor.select(QtGui.QTextCursor.LineUnderCursor)
    # update the text-edit
    self.recipient.setTextCursor(cursor)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336