使用QTextCursor复制所选文本

时间:2014-12-28 16:41:37

标签: python copy selection pyside qtextcursor

这些是我的小部件,

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

我想要做的是使用QTextCursor复制QTextEdit中的所选文字。我尝试过函数selectedText(),但它给了我一个空字符串。以下是我尝试打印的方法:

print('%s' % (self.cursor.selectedText()))

1 个答案:

答案 0 :(得分:2)

您需要从文本编辑中检索当前光标:

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

但请注意,此光标只是一个副本。如果您对其进行更改,则这些更改不会立即更新文本编辑。为此,您需要重置光标,如下所示:

    # make some changes to the cursor
    cursor.select(QtGui.QTextCursor.LineUnderCursor)
    # update the text-edit
    self.recipient.setTextCursor(cursor)