Search code examples
pythoncopyselectionpysideqtextcursor

Copying selected text with QTextCursor


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()))

Solution

  • 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)