您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在python中使用QPrinter打印控件,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
打印圖像是圖像處理軟件中的一個(gè)常用功能,打印圖像實(shí)際上是在QPaintDevice中畫圖,與平時(shí)在QWidget。QPixmap和QImage中畫圖是一樣的,都是創(chuàng)建一個(gè)QPainter對象進(jìn)行畫圖的,只是打印使用的是QPrinter,它的本質(zhì)上也是一個(gè)QPainterDevice(繪圖設(shè)備)
import sys from PyQt5.QtWidgets import QApplication,QMainWindow,QLabel,QSizePolicy,QAction from PyQt5.QtPrintSupport import QPrintDialog,QPrinter from PyQt5.QtGui import QImage,QIcon,QPixmap class MainWindow(QMainWindow): def __init__(self,parent=None): super(MainWindow, self).__init__(parent) #設(shè)置標(biāo)題 self.setWindowTitle('打印圖片') #創(chuàng)建標(biāo)簽,設(shè)置標(biāo)簽的大小規(guī)則以及控件的位置居中 self.imageLabel=QLabel() self.imageLabel.setSizePolicy(QSizePolicy.Ignored,QSizePolicy.Ignored) self.setCentralWidget(self.imageLabel) #實(shí)例化Qimage類 self.image = QImage() #自定義的多個(gè)函數(shù),實(shí)現(xiàn)的功能不一 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): #加載圖標(biāo),添加快捷方式,添加提示信息,綁定槽函數(shù) self.PrintAction=QAction(QIcon('images\screen.png'),self.tr('打印'),self) self.PrintAction.setShortcut('Ctrl+P') self.PrintAction.setStatusTip(self.tr('打印')) self.PrintAction.triggered.connect(self.slotPrint) def createMenus(self): #實(shí)例化菜單欄,并添加一個(gè)父菜單,以及把PrintAction添加到父菜單下 PrintMenu=self.menuBar().addMenu(self.tr('打印')) PrintMenu.addAction(self.PrintAction) def createToolBars(self): #在工具欄區(qū)域內(nèi)添加控件printACtion fileToolBar=self.addToolBar('Print') fileToolBar.addAction(self.PrintAction) def slotPrint(self): #實(shí)例化打印圖像對象 printer=QPrinter() #打印窗口彈出 printDialog=QPrintDialog(printer,self) if printDialog.exec_(): painter=QPainter(printer) #實(shí)例化視圖窗口 rect=painter.viewport() #獲取圖片的尺寸 size=self.image.size() size.scale(rect.size(),Qt.KeepAspectRatio) #設(shè)置視圖窗口的屬性 painter.setViewport(rect.x(),rect.y(),size.width(),size.height()) #設(shè)置窗口的大小為圖片的尺寸,并在窗口內(nèi)繪制圖片 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_())
運(yùn)行程序,顯示效果如下
打印功能
關(guān)于怎么在python中使用QPrinter打印控件就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。