在PyQt5中也是可以使用剪切板的, 其实就是只要实例化有一个剪切板对象,往里面存入或者提取想要的内容, 即可.

代码示范

闲话不多说, 上代码.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""
剪切板的使用, 当然你也可以自己去复制, 然后使用这里的粘贴按钮
"""
import sys,math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class CopyPasterDemo(QWidget):
def __init__(self):
super().__init__()
self.setUi()

def setUi(self):
self.setWindowTitle("copy paster 的使用")
self.resize(900, 900)
layout = QFormLayout()
line_edit = QLineEdit()
line_edit.setPlaceholderText("what are you doing?")
line_display = QLineEdit()
layout.addRow(line_edit)
layout.addRow(line_display)
html_edit = QTextEdit()
html_edit.setPlaceholderText("html for you want?")
html_display_edit = QTextEdit()
layout.addRow(html_edit, html_display_edit)
lable_img_you_choose = QLabel()
lable_img_you_choose.setPixmap(QPixmap("../images/boy.png"))
lable_img_paste = QLabel()
layout.addRow(lable_img_you_choose, lable_img_paste)
button_copy_text = QPushButton("复制文本")
button_copy_text.clicked.connect(lambda :self.copy_text("hello"))
button_paste_text = QPushButton("黏贴文本")
button_paste_text.clicked.connect(lambda : self.paste_text(line_display))
layout.addRow(button_copy_text, button_paste_text)
button_copy_html = QPushButton("复制html")
button_copy_html.clicked.connect(lambda : self.copy_html('<b>Bold and <font color=red>Red</font></b>'))
button_paste_html = QPushButton("粘贴html")
button_paste_html.clicked.connect(lambda : self.paste_html(html_display_edit))
layout.addRow(button_copy_html, button_paste_html)
button_copy_picture = QPushButton("复制picture")
button_copy_picture.clicked.connect(lambda : self.copy_img("../images/boy.png"))
button_paste_picture = QPushButton("粘贴picture")
button_paste_picture.clicked.connect(lambda : self.paste_img(lable_img_paste))
layout.addRow(button_copy_picture, button_paste_picture)
self.setLayout(layout)

def copy_text(self, text):
# 创建一个剪切板对象
clipboard = QApplication.clipboard()
clipboard.setText(text)

def paste_text(self, obj):
clipboard = QApplication.clipboard()
# 把剪切板的内容赋值给指定的对象
obj.setText(clipboard.text())

def copy_html(self, html):
# 创建一个数据结构对象
mimeData = QMimeData()
mimeData.setHtml(html)
clipboard = QApplication.clipboard()
clipboard.setMimeData(mimeData)

def paste_html(self, obj):
clipboard = QApplication.clipboard()
mimeData = clipboard.mimeData()
if mimeData.hasHtml():
obj.setText(mimeData.html())

def copy_img(self, img_path):
clipboard = QApplication.clipboard()
clipboard.setPixmap(QPixmap(img_path))

def paste_img(self, obj):
clipboard = QApplication.clipboard()
# 把剪切板里的图片放到指定的容器中
obj.setPixmap(QPixmap(clipboard.pixmap()))


if __name__ == '__main__':
app = QApplication(sys.argv)
window = CopyPasterDemo()
window.show()
app.exit(app.exec_())