使用pyqt5生成SVG文件 [英] Generate a SVG file with pyqt5
问题描述
我想使用pyqt5使用Python绘制一些简单的矢量图像.
I want to use pyqt5 to draw some simple vectorial images using Python.
到目前为止,我已经设法使用以下代码生成图像:
So far, I've managed to generate an image with the following code:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class MyPainter(QImage):
def __init__(self):
super().__init__(400, 400, QImage.Format_RGB32)
self.fill(Qt.black)
painter = QPainter(self)
painter.setPen(QPen(Qt.red, 8))
painter.drawRect(40, 40, 200, 100)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = MyPainter()
w.save('test.png', 'PNG')
绘制以下图像:
除了绘制SVG外,我想做同样的事情.
I want to do the same thing but rendering a SVG.
pyqt5.qtsvg模块可以吗?如何将其插入上面的代码中?我只是找不到任何例子.
Is it possible with pyqt5.qtsvg module? How would it be inserted in the code above? I just can't find any example.
推荐答案
我终于找到了解决方案:
I finally found the solution:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtSvg import *
if __name__ == "__main__":
generator = QSvgGenerator()
generator.setFileName("test.svg")
generator.setSize(QSize(400, 400))
generator.setViewBox(QRect(0, 0, 400, 400))
painter = QPainter(generator)
painter.fillRect(QRect(0, 0, 400, 400), Qt.black)
painter.setPen(QPen(Qt.red, 8))
painter.drawRect(40, 40, 200, 100)
painter.end()
QtSvg实际上提供了一个生成器,该生成器被用作QPainter()的参数.
QtSvg actually provides a generator which that is taken as an argument to the QPainter().
此外,我想做的是比使用无用的类更好的脚本"方式.
Also, what I want to do is better in a "script" way than using a useless class.
我也不需要QApplication,只需要绘画过程,就可以大大加快该过程.
I also don't need a QApplication, only the painting process, which accelerates the process quite much.
这篇关于使用pyqt5生成SVG文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!