本文共 1620 字,大约阅读时间需要 5 分钟。
import sysfrom PyQt5 import QtCorefrom PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtCore import *from PyQt5.QtPrintSupport import QPageSetupDialog,QPrintDialog,QPrinterclass Win(QMainWindow): def __init__(self): super().__init__() self.setGeometry(300, 300,500, 400) self.setWindowTitle('QPrinter的使用') self.printer = QPrinter() self.editor = QTextEdit(self) self.editor.setGeometry(20,20,300,270) self.openButton = QPushButton('打开文件',self) self.openButton.move(350,20) self.settingsButton = QPushButton('打印设置',self) self.settingsButton.move(350,50) self.printButton = QPushButton('打印文档',self) self.printButton.move(350,80) self.openButton.clicked.connect(self.openFile) self.settingsButton.clicked.connect(self.showSettingsDialog) self.printButton.clicked.connect(self.showPrintDialog) #打开文件 def openFile(self): frame = QFileDialog.getOpenFileName(self,'打开文本文件','./') if frame[0]: with open(frame[0],'r',encoding='utf-8',errors='ignore') as f: self.editor.setText(f.read()) #显示打印设置对话框 def showSettingsDialog(self): printDialog = QPageSetupDialog(self.printer,self) printDialog.exec() #显示打印文档对话框 def showPrintDialog(self): printDialog = QPrintDialog(self.printer,self) if(QDialog.Accepted == printDialog.exec_()): self.editor.print(self.printer)if __name__ == "__main__": app = QApplication(sys.argv) form = Win() form.show() sys.exit(app.exec_())
运行效果如下:
转载地址:http://utozi.baihongyu.com/