python - PyQt 打印 QWidget

标签 python pyqt pyqt4 qpainter qprinter

我正在尝试遵循 printing a QWidet 的文档并收到错误。当我运行以下代码时,我得到QPaintDevice:无法销毁正在绘制的绘画设备

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

最佳答案

用于优化的 QPainter 不会同时应用所有任务,但它会保留指令并在最后应用它们,但要强制执行该任务,最好调用 end() 方法或用它删除,因为销毁器也会调用end(),此外 QPainter 不必是该类的成员:

def print_me(self):
    printer = QtGui.QPrinter()
    printer.setOutputFormat(QtGui.QPrinter.PdfFormat)
    printer.setOutputFileName("Test.pdf")

    painter = QtGui.QPainter(printer)
    xscale = printer.pageRect().width() / self.width()
    yscale = printer.pageRect().height() / self.height()
    scale = min(xscale, yscale)
    painter.translate(printer.paperRect().center())
    painter.scale(scale, scale)
    painter.translate((self.width() / 2) * -1, (self.height() / 2) * -1)

    self.render(painter)
    painter.end()
    # or
    # del painter

关于python - PyQt 打印 QWidget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58667932/

相关文章:

python - 如何在一个进程中连续多次启动 pyqt GUI?

python - 如何使用线程自动关闭 PyQt/PySide 窗口?

python - 找到序列的最长准常数子序列

python - 如果尚未下载,请从列表中下载文件

python - 如何一次读取文件 N 行?

python - 从pyqt中的框架中删除所有内容

python - 防止在 QStyledItemDelegate 中编辑 ComboBox

python - pyqt - 如何制作一个文本区域来写入消息 - 有点像打印到控制台

python - PyQt : Trying to understand graphics scene/view

Python time.clock() - 使用线程重置时钟值