PyQt QLineEdit and 'paste' event?

Question:

I searched everywhere but couldn’t find an example on triggering a slot/event when text gets pasted in an PyQt4 QLineEdit ?

Asked By: Stacked

||

Answers:

You will have to define it yourself by overriding “keyPressEvent”. For Example:

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_()
Answered By: VIKASH JAISWAL

Add the following code to your MyForm class:

Inside __init__()

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

Define new method:

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

Define another method:

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
Answered By: qurban

Capture the CTRL-V and then process the text before pasting it into the Edit.

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)
Answered By: QuentinJS
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.