我正在尝试按照文档打印 QWidet并遇到错误。当我运行以下代码时,我得到QPaintDevice: Cannot destroy paint device that is being painted
.
import sys
from PyQt4 import QtGui, QtCore
class SampleApp(QtGui.QDialog):
def __init__(self):
super().__init__()
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
text_editor = QtGui.QTextEdit()
layout.addWidget(text_editor)
button = QtGui.QPushButton("Print")
layout.addWidget(button)
button.clicked.connect(self.print_me)
def print_me(self):
printer = QtGui.QPrinter()
printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
printer.setOutputFileName("Test.pdf")
self.painter = QtGui.QPainter(printer)
margins = printer.getPageMargins(QtGui.QPrinter.DevicePixel)
xscale = (printer.pageRect().width() - margins[0]) / self.width()
yscale = (printer.pageRect().height() - margins[1]) / self.height()
scale = min(xscale, yscale)
self.painter.scale(scale, scale)
self.render(self.painter)
app = QtGui.QApplication(sys.argv)
ex = SampleApp()
ex.show()
sys.exit(app.exec_())
如果我将 print_me() 方法更改为以下内容,它确实可以工作(当然,我只是失去了缩放画家的所有能力):
def print_me(self):
printer = QtGui.QPrinter()
printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
printer.setOutputFileName("Test.pdf")
self.render(QtGui.QPainter(printer))