printing from main page in pyqt5

梦想与她 提交于 2019-12-11 06:54:39

问题


i write some code in pyqt5 that create a table in main main:

class Ui_MainWindow(object):
    def setupUi(self, MainWindow): ...
    def retranslateUi(self, MainWindow):...
        self.pushButton.setText(_translate("MainWindow", "print"))
        self.pushButton.clicked.connect(self.printer)
    def printer(self):...

and use this class by:

app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())

i wanna know how can i print from main page of my program?


回答1:


This can be done rather easy using QPrinter class.

Below is well-commented example of how to do it.

import sys

from PyQt5 import QtGui, QtWidgets, QtPrintSupport


class App(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        # Create some widgets
        self.setGeometry(500, 500, 300, 300)
        self.button = QtWidgets.QPushButton(
            'Print QTextEdit widget (the one below)', self)
        self.button.setGeometry(20, 20, 260, 30)
        self.editor = QtWidgets.QTextEdit(
            'Wow such text why not change me?', self)
        self.editor.setGeometry(20, 60, 260, 200)
        self.button.clicked.connect(self.print_widget)

    def print_widget(self):
        # Create printer
        printer = QtPrintSupport.QPrinter()
        # Create painter
        painter = QtGui.QPainter()
        # Start painter
        painter.begin(printer)
        # Grab a widget you want to print
        screen = self.editor.grab()
        # Draw grabbed pixmap
        painter.drawPixmap(10, 10, screen)
        # End painting
        painter.end()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    gui = App()
    gui.show()
    app.exec_()

To print whole window just replace screen = self.editor.grab() with screen = self.grab()



来源:https://stackoverflow.com/questions/42455904/printing-from-main-page-in-pyqt5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!