1、使用剪切板
import sys,math
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Clipboard(QDialog):
def __init__(self):
super(Clipboard,self).__init__()
#定义六个复制粘贴按钮,用来实现复制粘贴文本,图像和HTML网页
textcopybutton=QPushButton("复制文本")
textpastebutton=QPushButton("粘贴文本")
imagecopybutton = QPushButton("复制图像")
imagepastebutton = QPushButton("粘贴图像")
htmlcopybutton = QPushButton("复制HTML网页")
htmlpastebutton = QPushButton("粘贴HTML网页")
self.textlabel=QLabel("默认字体") #显示粘贴的文本label
self.imagelabel=QLabel() #显示图像的label
self.imagelabel.setPixmap(QPixmap("./image-1/1-1.jpg"))
#定义网格栅格布局
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("剪切板")
def copytext(self):
clipboard=QApplication.clipboard()
clipboard.setText("hello world")
def pastetext(self):
clipboard = QApplication.clipboard()
self.textlabel.setText(clipboard.text())
def copyimage(self):
clipboard = QApplication.clipboard()
clipboard.setPixmap(QPixmap("./image-1/1-1.jpg"))
def pasteimage(self):
clipboard = QApplication.clipboard()
self.iamgelabel.setPixmap(clipboard.pixmap())
def copyhtml(self):
mimedata=QMimeData()
mimedata.setHtml('<b>Bold and <font color=red>Red</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)
p=Clipboard()
p.show()
sys.exit(app.exec_())