[파이썬] PyQt 클립보드 관리

PyQt is a Python binding for the Qt toolkit. It allows you to create powerful and cross-platform applications with a rich set of features. One of the useful features provided by PyQt is the ability to manage the system clipboard. In this blog post, we will explore how to use PyQt to interact with the clipboard in Python.

Installing PyQt

Before we start working with PyQt, we need to install it. You can install PyQt by running the following command in your terminal:

pip install pyqt5

Accessing the Clipboard

To access the clipboard in PyQt, we need to import the QClipboard class from the PyQt5.QtWidgets module. We can then create an instance of the QClipboard class to work with the clipboard.

Here is an example that demonstrates how to retrieve the text from the clipboard:

from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QClipboard

# Create an instance of QApplication
app = QApplication([])

# Get the clipboard
clipboard = QApplication.clipboard()

# Retrieve the text from the clipboard
text = clipboard.text()

# Print the retrieved text
print(text)

# Clean up
app.exit()

Modifying the Clipboard

In addition to retrieving the clipboard data, we can also modify the contents of the clipboard. We can use the setText() method of the QClipboard class to set the text to be copied to the clipboard.

Here is an example that shows how to set a custom text to the clipboard:

from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QClipboard

# Create an instance of QApplication
app = QApplication([])

# Get the clipboard
clipboard = QApplication.clipboard()

# Set the text to be copied to the clipboard
clipboard.setText("Hello, World!")

# Print a message after copying the text
print("Text copied to the clipboard!")

# Clean up
app.exit()

Conclusion

In this blog post, we explored how to use PyQt to manage the clipboard in Python. We learned how to retrieve the text from the clipboard using the QClipboard class, as well as how to modify the clipboard contents using the setText() method. With these tools, you can incorporate clipboard functionality into your PyQt applications and enhance the user experience.

Remember to import the necessary modules and install PyQt before running the code examples. Happy coding!