PyQt5打印机

Posted yanjy-onlyone

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PyQt5打印机相关的知识,希望对你有一定的参考价值。

1、打印机操作(打印默认文本里面的内容)
from PyQt5 import QtGui,QtWidgets,QtPrintSupport
from PyQt5.QtWidgets import *
import sys

class Printsupport1(QMainWindow):
def __init__(self):
super(Printsupport1,self).__init__()
self.setGeometry(500,200,300,300)
self.button=QPushButton("打印QtextEdit控件中的内容",self)
self.button.setGeometry(20,60,260,200)
self.editor=QTextEdit("默认文本",self)
self.button.clicked.connect(self.print)

def print(self):
printer=QtPrintSupport.QPrinter() #打印机

painter=QtGui.QPainter()
#将绘制的目标重新定向到打印机
painter.begin(printer)
screen=self.editor.grab()
painter.drawPixmap(10,10,screen)
painter.end()
print("print")

if __name__=="__main__":
app=QApplication(sys.argv)
p=Printsupport1()
p.show()
sys.exit(app.exec_())

技术图片

2、显示打印样式设置对话框
from PyQt5.QtPrintSupport import QPageSetupDialog,QPrintDialog,QPrinter
from PyQt5.QtWidgets import *
import sys

class Printdialog(QMainWindow):
def __init__(self):
super(Printdialog,self).__init__()
self.printer=QPrinter() #定义一个默认的打印机
self.initUI()

def initUI(self):
self.setGeometry(300,300,500,400)
self.setWindowTitle("打印对话框")
self.editor=QTextEdit(self)
self.editor.setGeometry(20,20,300,270)

self.openbutton=QPushButton("打开文件",self)
self.openbutton.move(350,20)

self.settingbutton=QPushButton("打印设置",self)
self.settingbutton.move(350,50)

self.printbutton=QPushButton("打印文档",self)
self.printbutton.move(350,80)

self.openbutton.clicked.connect(self.openfile)
self.settingbutton.clicked.connect(self.showsettingdailog)
self.printbutton.clicked.connect(self.showprintdialog)
#打开文件
def openfile(self):
fname=QFileDialog.getOpenFileName(self,"打开文本文件","./")
if fname[0]:
with open(fname[0],"r",encoding=‘utf-8‘,errors=‘ignore‘) as f:
self.editor.setText(f.read())

#显示打印设置对话框
def showsettingdailog(self):
printerdailog=QPageSetupDialog(self.printer,self)
printerdailog.exec()

#显示打印对话框
def showprintdialog(self):
print1=QPrintDialog(self.printer,self)
if QDialog.Accepted==print1.exec():
self.editor.print(self.printer)

if __name__=="__main__":
app=QApplication(sys.argv)
p=Printdialog()
p.show()
sys.exit(app.exec_())

技术图片

以上是关于PyQt5打印机的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 PyQt5 打印预览图像?

pyqt5-打印

PyQt5中的信息打印,print 函数的重定向和再封装

如何在pyqt5 QlistWidget中选择多个项目并打印它们[重复]

根据从导入包中打印的标准输出更新 PyQt 进度条(PyQt5)

如何在Qprinter pyqt5中打印带有图像的html页面