问题
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')
Which draws the following image:
I want to do the same thing but rendering a SVG.
Is it possible with pyqt5.qtsvg module? How would it be inserted in the code above? I just can't find any example.
回答1:
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 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.
I also don't need a QApplication, only the painting process, which accelerates the process quite much.
来源:https://stackoverflow.com/questions/57432570/generate-a-svg-file-with-pyqt5