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:
Connect to the clipboard:
QApplication.clipboard().dataChanged.connect()
Fetch the current clipboard contents:
QApplication.clipboard().text()
Below is a visual representation of how the PyQt clipboard integration looks:
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 |
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.
