2

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:

Generated 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.

Benjamin Barrois
  • 2,566
  • 13
  • 30

1 Answers1

0

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.

Benjamin Barrois
  • 2,566
  • 13
  • 30