<p>为了做你想做的事情,你可以子类<code>QLineEdit</code>,并创建一个提供你想要的自定义粘贴功能的方法(<code>paste</code>方法不是虚拟的,因此如果它被重写,就不会从Qt代码调用它)。此外,您还需要一个事件过滤器来截获CTRL+V的快捷方式。您可能还需要过滤鼠标中键,它也用于粘贴剪贴板内容。从事件筛选器中,您可以调用替换的<code>paste</code>方法。在</p>
<p>您可以使用以下代码作为起点:</p>
<pre><code>import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class myEditor(QLineEdit):
def __init__(self, parent=None):
super(myEditor, self).__init__(parent)
def myPaste(self):
self.insert("custom text pasted! ")
class myWindow(QMainWindow):
def __init__(self, parent=None):
super(myWindow, self).__init__(parent)
self.customEditor = myEditor(self)
self.setCentralWidget(self.customEditor)
self.customEditor.installEventFilter(self)
def eventFilter(self, obj, e):
if (obj == self.customEditor):
if (e.type() == QEvent.KeyPress):
if (e.matches(QKeySequence.Paste)):
self.customEditor.myPaste()
return True
return False
else:
return QMainWindow.eventFilter(obj, e)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = myWindow()
window.show()
app.exec_()
</code></pre>
<p>这里的事件过滤器只负责粘贴的键盘快捷键。正如我所说,你还需要考虑其他来源的粘贴操作。在</p>