Python Qt GUI设计:QClipboard剪贴数据类(基础篇—19)

QClipboard类提供了对系统剪贴板的访问,可以在应用程序之间复制和粘贴数据,它的操作类似于QDrag类,使用类似的数据类型。

QApplication类有一个静态方法clipboard(),它返回对剪贴板对象的引用。任何类型的MimeData都可以从剪贴板复制或粘贴。

QClipboard类中的常用方法如下表所示:

QClipboard类中的常用信号如下表所示:

通过示例了解QClipboard剪贴数据类,示例效果如下所示: 

示例中,有6个按钮和2个标签。需要实例化clipboard对象,可以将文本复制到clipboard对象中,也可以将图片复制到剪贴板对象中。

实现代码如下所示:

  1. import os
  2. import sys
  3. from PyQt5.QtCore import QMimeData
  4. from PyQt5.QtWidgets import (QApplication, QDialog, QGridLayout, QLabel,QPushButton)
  5. from PyQt5.QtGui import QPixmap
  6. class Form(QDialog):
  7. def __init__(self, parent=None):
  8. super(Form, self).__init__(parent)
  9. textCopyButton = QPushButton("&Copy Text")
  10. textPasteButton = QPushButton("Paste &Text")
  11. htmlCopyButton = QPushButton("C&opy HTML")
  12. htmlPasteButton = QPushButton("Paste &HTML")
  13. imageCopyButton = QPushButton("Co&py Image")
  14. imagePasteButton = QPushButton("Paste &Image")
  15. self.textLabel = QLabel("Original text")
  16. self.imageLabel = QLabel()
  17. self.imageLabel.setPixmap(QPixmap(os.path.join(
  18. os.path.dirname(__file__), "images/clock.png")))
  19. layout = QGridLayout()
  20. layout.addWidget(textCopyButton, 0, 0)
  21. layout.addWidget(imageCopyButton, 0, 1)
  22. layout.addWidget(htmlCopyButton, 0, 2)
  23. layout.addWidget(textPasteButton, 1, 0)
  24. layout.addWidget(imagePasteButton, 1, 1)
  25. layout.addWidget(htmlPasteButton, 1, 2)
  26. layout.addWidget(self.textLabel, 2, 0, 1, 2)
  27. layout.addWidget(self.imageLabel, 2, 2)
  28. self.setLayout(layout)
  29. textCopyButton.clicked.connect(self.copyText)
  30. textPasteButton.clicked.connect(self.pasteText)
  31. htmlCopyButton.clicked.connect(self.copyHtml)
  32. htmlPasteButton.clicked.connect(self.pasteHtml)
  33. imageCopyButton.clicked.connect(self.copyImage)
  34. imagePasteButton.clicked.connect(self.pasteImage)
  35. self.setWindowTitle("Clipboard 例子")
  36. def copyText(self):
  37. clipboard = QApplication.clipboard()
  38. clipboard.setText("不脱发的程序猿")
  39. def pasteText(self):
  40. clipboard = QApplication.clipboard()
  41. self.textLabel.setText(clipboard.text())
  42. def copyImage(self):
  43. clipboard = QApplication.clipboard()
  44. clipboard.setPixmap(QPixmap(os.path.join(
  45. os.path.dirname(__file__), "./4.jpg")))
  46. def pasteImage(self):
  47. clipboard = QApplication.clipboard()
  48. self.imageLabel.setPixmap(clipboard.pixmap())
  49. def copyHtml(self):
  50. mimeData = QMimeData()
  51. mimeData.setHtml("<b>公众号:美男子玩编程</font></b>")
  52. clipboard = QApplication.clipboard()
  53. clipboard.setMimeData(mimeData)
  54. def pasteHtml(self):
  55. clipboard = QApplication.clipboard()
  56. mimeData = clipboard.mimeData()
  57. if mimeData.hasHtml():
  58. self.textLabel.setText(mimeData.html())
  59. if __name__ == "__main__":
  60. app = QApplication(sys.argv)
  61. form = Form()
  62. form.show()
  63. sys.exit(app.exec_())

关注公众号,发送关键字:Java车牌识别,获取项目源码。