1

我在 pyqt5 中编写了一些代码,在 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):...

并通过以下方式使用此类:

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

我想知道如何从程序的主页打印?

4

1 回答 1

5

使用QPrinter类可以很容易地做到这一点。

下面是如何做到这一点的评论很好的例子。

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_()

要打印整个窗口,只需替换screen = self.editor.grab()screen = self.grab()

于 2017-03-01T07:58:41.267 回答