Python Qt GUI设计:QClipboard剪贴数据类(基础篇—19)
QClipboard类提供了对系统剪贴板的访问,可以在应用程序之间复制和粘贴数据,它的操作类似于QDrag类,使用类似的数据类型。
QApplication类有一个静态方法clipboard(),它返回对剪贴板对象的引用。任何类型的MimeData都可以从剪贴板复制或粘贴。
QClipboard类中的常用方法如下表所示:
QClipboard类中的常用信号如下表所示:
通过示例了解QClipboard剪贴数据类,示例效果如下所示:
示例中,有6个按钮和2个标签。需要实例化clipboard对象,可以将文本复制到clipboard对象中,也可以将图片复制到剪贴板对象中。
实现代码如下所示:
- import os
- import sys
- from PyQt5.QtCore import QMimeData
- from PyQt5.QtWidgets import (QApplication, QDialog, QGridLayout, QLabel,QPushButton)
- from PyQt5.QtGui import QPixmap
-
- class Form(QDialog):
- def __init__(self, parent=None):
- super(Form, self).__init__(parent)
- textCopyButton = QPushButton("&Copy Text")
- textPasteButton = QPushButton("Paste &Text")
- htmlCopyButton = QPushButton("C&opy HTML")
- htmlPasteButton = QPushButton("Paste &HTML")
- imageCopyButton = QPushButton("Co&py Image")
- imagePasteButton = QPushButton("Paste &Image")
- self.textLabel = QLabel("Original text")
- self.imageLabel = QLabel()
- self.imageLabel.setPixmap(QPixmap(os.path.join(
- os.path.dirname(__file__), "images/clock.png")))
- layout = QGridLayout()
- layout.addWidget(textCopyButton, 0, 0)
- layout.addWidget(imageCopyButton, 0, 1)
- layout.addWidget(htmlCopyButton, 0, 2)
- layout.addWidget(textPasteButton, 1, 0)
- layout.addWidget(imagePasteButton, 1, 1)
- layout.addWidget(htmlPasteButton, 1, 2)
- layout.addWidget(self.textLabel, 2, 0, 1, 2)
- layout.addWidget(self.imageLabel, 2, 2)
- self.setLayout(layout)
- textCopyButton.clicked.connect(self.copyText)
- textPasteButton.clicked.connect(self.pasteText)
- htmlCopyButton.clicked.connect(self.copyHtml)
- htmlPasteButton.clicked.connect(self.pasteHtml)
- imageCopyButton.clicked.connect(self.copyImage)
- imagePasteButton.clicked.connect(self.pasteImage)
- self.setWindowTitle("Clipboard 例子")
-
- def copyText(self):
- clipboard = QApplication.clipboard()
- clipboard.setText("不脱发的程序猿")
-
- def pasteText(self):
- clipboard = QApplication.clipboard()
- self.textLabel.setText(clipboard.text())
-
- def copyImage(self):
- clipboard = QApplication.clipboard()
- clipboard.setPixmap(QPixmap(os.path.join(
- os.path.dirname(__file__), "./4.jpg")))
-
- def pasteImage(self):
- clipboard = QApplication.clipboard()
- self.imageLabel.setPixmap(clipboard.pixmap())
-
- def copyHtml(self):
- mimeData = QMimeData()
- mimeData.setHtml("<b>公众号:美男子玩编程</font></b>")
- clipboard = QApplication.clipboard()
- clipboard.setMimeData(mimeData)
-
- def pasteHtml(self):
- clipboard = QApplication.clipboard()
- mimeData = clipboard.mimeData()
- if mimeData.hasHtml():
- self.textLabel.setText(mimeData.html())
-
- if __name__ == "__main__":
- app = QApplication(sys.argv)
- form = Form()
- form.show()
- sys.exit(app.exec_())
关注公众号,发送关键字:Java车牌识别,获取项目源码。