问题描述
我在 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渲染,错误地忽略了画笔的缩放。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)