python GUI庫圖形界面開發(fā)之PyQt5打印控件QPrinter詳細使用方法與實例
更新時間:2020年02月28日 16:20:19 作者:jia666666
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5打印控件QPrinter詳細使用方法與實例,需要的朋友可以參考下
PyQt5打印控件QPrinter簡介
打印圖像是圖像處理軟件中的一個常用功能,打印圖像實際上是在QPaintDevice中畫圖,與平時在QWidget。QPixmap和QImage中畫圖是一樣的,都是創(chuàng)建一個QPainter對象進行畫圖的,只是打印使用的是QPrinter,它的本質(zhì)上也是一個QPainterDevice(繪圖設(shè)備)
QPrinter的使用實例
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)
#實例化Qimage類
self.image = QImage()
#自定義的多個函數(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):
#實例化菜單欄,并添加一個父菜單,以及把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):
#實例化打印圖像對象
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)
#設(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_())
運行程序,顯示效果如下

打印功能

本文詳細講解了PyQt5打印控件QPrinter詳細使用方法與實例,更多關(guān)于PyQt5控件知識請查看下面的相關(guān)鏈接
相關(guān)文章
解決Jupyter無法導(dǎo)入已安裝的 module問題
這篇文章主要介紹了解決Jupyter無法導(dǎo)入已安裝的 module問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04

