我在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_())
我想知道如何从我的程序主页打印?
答案 0 :(得分:2)
使用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()