PyQt5最全38 打印对话框之QPrintDialog显示打印对话框
import sys
from PyQt5.QtPrintSupport import QPageSetupDialog, QPrintDialog, QPrinter
from PyQt5.QtWidgets import *
class PrintDialog(QMainWindow):
"""
显示打印对话框
QFileDialog
QPageSetupDialog
QPrintDialog
"""
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.showSettingsDialog)
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 showSettingsDialog(self):
printerDialog = QPageSetupDialog(self)
printerDialog.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)
main = PrintDialog()
print(main.__doc__)
main.show()
sys.exit(app.exec_())
结果
点击打开文件 选择文件打开以后,点击打印设置 打印文档,可以另存为pdf测试
|