Python

pyqt clipboard

The clipboard holds data you copy and paste. You can copy text from one program to another, like copying text from a website into notepad.

We will create a program that has access to the clipboard using PyQt. If we copy text from any program, it will be added into the textarea of the PyQt application.

pyqt clipboard

Related course:
Create Simple GUI Applications with Python and Qt

Clipboard example

We can access the clipboard using the class QClipboard. Then we can output that text. We connect the clipboard to a method using the line:

QApplication.clipboard().dataChanged.connect()

Then we grab the contents using
QApplication.clipboard().text()

Try the example below
# PyQt5 clipboard
#
# Gets text from the system clipboard
# If you copy text to the clipboard,
# output is shown in the console.
#
# pythonprogramminglanguage.com
#

import sys
from PyQt5.Qt import QApplication, QClipboard
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QPlainTextEdit
from PyQt5.QtCore import QSize

class ExampleWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(440, 240))
self.setWindowTitle("PyQt5 Clipboard example")

# Add text field
self.b = QPlainTextEdit(self)
self.b.insertPlainText("Use your mouse to copy text to the clipboard.\nText can be copied from any application.\n")
self.b.move(10,10)
self.b.resize(400,200)

QApplication.clipboard().dataChanged.connect(self.clipboardChanged)

# Get the system clipboard contents
def clipboardChanged(self):
text = QApplication.clipboard().text()
print(text)
self.b.insertPlainText(text + '\n')

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = ExampleWindow()
mainWin.show()
sys.exit( app.exec_() )

Previous Post Next Post

Cookie policy | Privacy policy | ©

PyQt