Skip to main content
 首页 » 编程设计

python之使用 QTextCursor 复制选定的文本

2024年10月25日11zhwl

这些是我拥有的小部件,

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

请您参考如下方法:

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

    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)