選單欄、工具欄與狀態列-QPrinter
阿新 • • 發佈:2020-08-07
列印影象是影象處理軟體中的一個常用功能。列印影象實際上是在QPaintDevice中畫圖,與平常在QWidget、QPixmap和QImage中畫圖一樣,都是建立一個QPainter物件進行畫圖的,只是列印使用的是QPrinter,它本質上也是一個QPaintDevice(繪圖裝置)。
案例37 QPrinter的使用
import sys from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QSizePolicy, QAction from PyQt5.QtGui import QIcon, QImage, QPixmap, QPainterfrom PyQt5.QtPrintSupport import QPrinter, QPrintDialog from PyQt5.QtCore import Qt class QPrinterDemo(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle(self.tr("列印圖片")) self.imageLabel = QLabel() self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.setCentralWidget(self.imageLabel) self.image= QImage() self.createActions() self.createMenus() self.createToolBars() if self.image.load("./images/screen.png"): self.imageLabel.setPixmap(QPixmap.fromImage(self.image)) self.resize(self.image.width(), self.image.height()) def createActions(self): self.PrintAction= QAction( QIcon("./images/printer.png"), self.tr("列印"), self ) self.PrintAction.setShortcut("Ctrl+P") self.PrintAction.setStatusTip(self.tr("列印")) self.PrintAction.triggered.connect(self.slotPrint) def createMenus(self): PrintMenu = self.menuBar().addMenu(self.tr("列印")) PrintMenu.addAction(self.PrintAction) def createToolBars(self): fileToolBar = self.addToolBar("Print") fileToolBar.addAction(self.PrintAction) def slotPrint(self): printer = QPrinter() printDialog = QPrintDialog(printer, self) if printDialog.exec_(): painter = QPainter(printer) rect = painter.viewport() size = self.image.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.image.rect()) painter.drawImage(0, 0, self.image) if __name__ == "__main__": app = QApplication(sys.argv) demo = QPrinterDemo() demo.show() sys.exit(app.exec_())