微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

QPrinter/QPdfWriter 忽略的 QBrush 转换

如何解决QPrinter/QPdfWriter 忽略的 QBrush 转换

我在 macOS 10.15.7 上使用 PyQt 5.15.2 (Qt 5.15.2)。 我正在尝试从 QGraphicsScene 生成 PDF。 我正在使用具有像素图纹理的画笔绘制一些路径,并应用了缩放转换(使用 Brush.setTransform)。 当我在 QGraphicsView 中显示场景时,我得到了所需的输出。 当我将相同的场景渲染到 QPrinter(设置为生成 pdf)时,会应用纹理但忽略转换。 这是一个已知的限制吗?有办法解决吗?

下面是一个最小的例子,在类似于我的用例的上下文中显示了问题。 在这里,我正在创建一个用于说明目的的纹理。 由于抗锯齿引起的渲染伪影与我的问题无关。 问题是渲染画笔中纹理的比例(设置为 0.5)与 pdf 输出中的比例(始终为 1)之间存在差异。 [要生成输出,只需双击视图,您将在当前路径中看到一个 test.pdf。]

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtPrintSupport import *

class Test(QGraphicsView):

  def __init__(self):
    QGraphicsView.__init__(self)

    # Here I am creating a texture for testing
    # it is a 50x50 black square
    s = 50
    img = QImage(s,s,QImage.Format_ARGB32)
    img.fill(Qt.transparent)
    for x in range(s):
      img.setPixelColor(x,Qt.black)
      img.setPixelColor(x,s-1,Qt.black)
      img.setPixelColor(s-1,x,Qt.black)
      img.setPixelColor(0,Qt.black)

    self.scene = QGraphicsScene()
    self.setScene(self.scene)
    r = self.scene.addRect(0,1404,1872)

    pen = QPen()
    pen.setWidth(150)
    pen.setCapStyle(Qt.RoundCap)
    pen.setJoinStyle(Qt.RoundJoin)

    b=QBrush(img)
    # Here I am transforming the brush so that the texture should be scaled 50% in both height and width
    tr = QTransform()
    tr.scale(.5,.5)
    b.setTransform(tr)
    pen.setBrush(b)

    # A random path for testing,drawn using the textured brush
    path = QPainterPath(QPointF(200,200))
    path.lineto(300,300)
    path.lineto(300,1000)
    path.lineto(700,700)
    self.pathItem = QGraphicsPathItem(path,r)
    self.pathItem.setPen(pen)

  def resizeEvent(self,event):
    self.fitInView(self.sceneRect(),Qt.KeepAspectRatio)

  def mouseDoubleClickEvent(self,event):
    printer = QPrinter(QPrinter.HighResolution)
    printer.setoutputFormat(QPrinter.PdfFormat)
    # printer.setPageSize(QPrinter.A4)
    printer.setoutputFileName("test.pdf")
    printer.setPaperSize(QSizef(1404,1872),QPrinter.Millimeter)
    printer.setPageMargins(0,QPrinter.Millimeter)
    p=QPainter()
    p.begin(printer)
    self.scene.render(p)
    p.end()

if __name__ == '__main__':
  app = QApplication([])
  print(QT_VERSION_STR)
  print(PYQT_VERSION_STR)
  viewer = test()
  viewer.show()
  app.exec_()

所需的输出在左侧,如 QGraphicsView 正确显示的那样。 右边是同一场景的PDF渲染,错误地忽略了画笔的缩放。

preview

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。