PyQt - QClipboard



The QClipboard class is a part of the PySide2.QtGui module in PyQt, offering a simple mechanism for copying and pasting data between applications. It supports various data types similar to QDrag, enabling the exchange of text, images, and custom MIME data.

QApplication class has a static method clipboard() which returns reference to clipboard object. Any type of MimeData can be copied to or pasted from the clipboard.

Methods in QClipboard

Following are the clipboard class methods that are commonly used −

Sr.No. Methods & Description
1

clear()

Clears clipboard contents

2

setImage()

Copies QImage into clipboard

3

setMimeData()

Sets MIME data into clipboard

4

setPixmap()

Copies Pixmap object in clipboard

5

setText()

Copies QString in clipboard

6

text()

Retrieves text from clipboard

Signal associated with clipboard object is −

Sr.No. Method & Description
1

dataChanged()

Whenever clipboard data changes

Example 1: Copying and Pasting Text

In the below example, we initialize a QApplication instance. Then we access the clipboard using QApplication.clipboard() and set text to the clipboard using setText(). Retrieve the pasted text using text().

from PyQt6.QtWidgets import QApplication
from PyQt6.QtGui import QClipboard

# Initialize application
app = QApplication([])

# Access clipboard
clipboard = QApplication.clipboard()

# Copy text to clipboard
clipboard.setText("Hello, PyQt!")

# Paste text from clipboard
pasted_text = clipboard.text()
print("Pasted Text:", pasted_text)

Output

Pasted Text: Hello, PyQt!

Example 2: Copying and Pasting Images

In the below example, we initialize a QApplication instance. Then we access the clipboard using QApplication.clipboard(). Set a pixmap (image) to the clipboard using setPixmap(). Retrieve the pasted pixmap (image) using pixmap() and save it as a file.

from PyQt6.QtWidgets import QApplication
from PyQt6.QtGui import QClipboard, QPixmap

# Initialize application
app = QApplication([])

# Access clipboard
clipboard = QApplication.clipboard()

# Copy image to clipboard
image_path = "python_logo.png"
pixmap = QPixmap(image_path)
clipboard.setPixmap(pixmap)

# Paste image from clipboard
pasted_pixmap = clipboard.pixmap()
pasted_pixmap.save("pasted_image.png")

Output

As output A new image file "pasted_image.png" is saved.

pyqt qclipboard example 2

Example 3: Clearing the Clipboard

In the below example, we initialize a QApplication instance. Access the clipboard using QApplication.clipboard().Then Clear the clipboard contents using clear().

from PyQt6.QtWidgets import QApplication
from PyQt6.QtGui import QClipboard

# Initialize application
app = QApplication([])

# Access clipboard
clipboard = QApplication.clipboard()

# Clear the clipboard
clipboard.clear()

Output

The contents of the clipboard gets cleared.
Advertisements