Python Qt GUI设计:QPrinter打印图片类(基础篇—21)
生活随笔
收集整理的這篇文章主要介紹了
Python Qt GUI设计:QPrinter打印图片类(基础篇—21)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
打印圖像是圖像處理軟件中的一個常用功能,打印圖像實際上是在QPaintDevice中畫圖,與平常在QWidget、QPixmap和Qlmage中畫圖一樣,都是創(chuàng)建一個QPainter對象進行畫圖的,只是打印使用的是QPrinter,它本質(zhì)上也是一個QPaintDevice(繪圖設備)。
通過一個示例了解QPrinter打印圖片類的使用,效果如下所示:
實現(xiàn)代碼如下所示:
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QImage , QIcon, QPixmap
from PyQt5.QtWidgets import QApplication , QMainWindow, QLabel, QSizePolicy , QAction
from PyQt5.QtPrintSupport import QPrinter, QPrintDialog
import sys class MainWindow(QMainWindow): def __init__(self,parent=None): super(MainWindow,self).__init__(parent) self.setWindowTitle(self.tr("打印圖片")) # 創(chuàng)建一個放置圖像的QLabel對象imageLabel,并將該QLabel對象設置為中心窗體。 self.imageLabel=QLabel() self.imageLabel.setSizePolicy(QSizePolicy.Ignored,QSizePolicy.Ignored) self.setCentralWidget(self.imageLabel) self.image=QImage() # 創(chuàng)建菜單,工具條等部件 self.createActions() self.createMenus() self.createToolBars() # 在imageLabel對象中放置圖像if self.image.load("./2.jpg"): self.imageLabel.setPixmap(QPixmap.fromImage(self.image)) self.resize(self.image.width(),self.image.height()) def createActions(self): self.PrintAction=QAction(QIcon("./2.jpg"),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): # 新建一個QPrinter對象 printer=QPrinter() # 創(chuàng)建一個QPrintDialog對象,參數(shù)為QPrinter對象 printDialog=QPrintDialog(printer,self) '''判斷打印對話框顯示后用戶是否單擊“打印”按鈕,若單擊“打印”按鈕,則相關打印屬性可以通過創(chuàng)建QPrintDialog對象時使用的QPrinter對象獲得,若用戶單擊“取消”按鈕,則不執(zhí)行后續(xù)的打印操作。 ''' if printDialog.exec_(): # 創(chuàng)建一個QPainter對象,并指定繪圖設備為一個QPrinter對象。painter=QPainter(printer) # 獲得QPainter對象的視口矩形rect=painter.viewport() # 獲得圖像的大小size=self.image.size() # 按照圖形的比例大小重新設置視口矩形size.scale(rect.size(),Qt.KeepAspectRatio) painter.setViewport(rect.x(),rect.y(),size.width(),size.height()) # 設置QPainter窗口大小為圖像的大小painter.setWindow(self.image.rect()) # 打印 painter.drawImage(0,0,self.image) if __name__ == "__main__": app=QApplication(sys.argv) main=MainWindow() main.show() sys.exit(app.exec_())
總結(jié)
以上是生活随笔為你收集整理的Python Qt GUI设计:QPrinter打印图片类(基础篇—21)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python Qt GUI设计:QCal
- 下一篇: Python Qt GUI设计:QTab