The clipboard is the place where a copy or cut goes. PyQt reaches it through QGuiApplication.clipboard(), so you can read and write text from any program.

With PyQt, it’s possible to create a program that not only accesses the clipboard’s content but also displays it in a user-friendly interface. So, if you’ve ever wondered how to manipulate clipboard contents using a PyQt application, this is the guide for you.

Accessing Clipboard with PyQt

At the core of clipboard management in PyQt is the QClipboard class. Through this class, developers can retrieve and display copied text. Here’s a step-by-step breakdown:

  1. Connect to the clipboard:

    QApplication.clipboard().dataChanged.connect()
  2. Fetch the current clipboard contents:

    QApplication.clipboard().text()

Below is a visual representation of how the PyQt clipboard integration looks:

Visual representation of PyQt clipboard integration

To further illustrate, let’s look at a practical example. The following code sets up a PyQt5 application that fetches and displays text copied to the system clipboard:

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):
super().__init__()
self.setMinimumSize(QSize(440, 240))
self.setWindowTitle("Clipboard Management with PyQt5")

# Initialize text field
self.b = QPlainTextEdit(self)
self.b.insertPlainText("Copy any text to the clipboard to see it displayed here.\nThis can be from any application or source.\n")
self.b.move(10,10)
self.b.resize(400,200)
QApplication.clipboard().dataChanged.connect(self.onClipboardChanged)

# Handle clipboard changes
def onClipboardChanged(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_() )

With the above code, whenever text is copied from any source, the PyQt application will instantly display it.

The methods

  • clipboard().setText('hello') puts text on the clipboard.
  • clipboard().text() reads it back.
  • clipboard().clear() empties it, useful in a Clear menu action.
  • It works with images too, clipboard().setImage(qimage).

The clipboard is owned by the operating system, not by your window, so the text stays there after you close the app. That is why a Clear button is a good idea.

Reading helps, writing fixes it. PyChallenge has exercises on this and you can try them right now.