繁体   English   中英

PyQt QLineEdit 和“粘贴”事件?

[英]PyQt QLineEdit and 'paste' event?

我到处搜索但找不到在 PyQt4 QLineEdit 中粘贴文本时触发插槽/事件的示例?

将以下代码添加到MyForm类中:

__init__()内部

self.ui.lineEdit_URL.textChanged.connect(self.valueChanged)

定义新方法:

def valueChanged(self, text):
     if QtGui.QApplication.clipboard().text() == text:
         self.pasteEvent(text)

定义另一种方法:

def pasteEvent(self, text):
    # this is your paste event, whenever any text is pasted in the
    # 'lineEdit_URL', this method gets called.
    # 'text' is the newly pasted text.

    print text

您将必须通过覆盖“ keyPressEvent”自己定义它。 例如:

from PyQt4 import QtGui, QtCore
import sys

class NoteText(QtGui.QLineEdit):
    def __init__(self, parent):
        super (NoteText, self).__init__(parent)

    def keyPressEvent(self, event):
        if event.matches(QtGui.QKeySequence.Paste):
            self.setText("Bye")

class Test(QtGui.QWidget):
  def __init__( self, parent=None):
      super(Test, self).__init__(parent)

      le = QtGui.QLineEdit()
      nt = NoteText(le)

      layout = QtGui.QHBoxLayout()
      layout.addWidget(nt)
      self.setLayout(layout)

app = QtGui.QApplication(sys.argv)
myWidget = Test()
myWidget.show()
app.exec_()

捕获 CTRL-V,然后在将其粘贴到编辑器之前处理文本。

import pyperclip

class MyLineEdit(QLineEdit):
    def __init__(self, parent):
        super (MyLineEdit, self).__init__(parent)

    def keyPressEvent(self, event):
        if event.modifiers() == Qt.KeyboardModifier.ControlModifier and event.key() == Qt.Key.Key_V:
            clipboard_content = pyperclip.paste()
            self.setText('hi' + clipboard_content)
        else:
            super().keyPressEvent(event)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM