PyQt 打印 QWidget [英] PyQt print QWidget

查看:86
本文介绍了PyQt 打印 QWidget的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照打印 QWidet 的文档进行操作,并且出现错误.当我运行以下代码时,我得到 QPaintDevice:无法销毁正在绘制的绘制设备.

Am trying to follow the documentation for printing a QWidet and am getting an error. When I run the following code I get 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() 方法更改为以下内容,它确实有效(当然,我只是失去了缩放画家的所有能力):

If I change the print_me() method to the following, it does however work (I just lose all of the ability to scale the painter of course):

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 不必是该类的成员:

QPainter for optimization does not apply all the tasks at the same time but it keeps instructions and applies them at the end but to force that task it is better to call the end() method or delete with it since the destroyer also calls end(), in addition it is not necessary for QPainter to be a member of the class:

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

这篇关于PyQt 打印 QWidget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆