PySide2: Load SVG from Variable rather than from file

61 Views Asked by At

I want to display an svg file using PySide. But I would prefer not having to create a file.svg and then load it using QSvgWidget

Rather I just have the file contents of the file.svg contents already stored in a variable as a string.

How would I go about directly loading the SVG from the variable rather than form the file.

Best

2

There are 2 best solutions below

0
user2314737 On BEST ANSWER

You need to convert the string to a QByteArray.

From the QSvgWidget.load documentation:

PySide6.QtSvgWidgets.QSvgWidget.load(contents)

PARAMETERS:

contents – PySide6.QtCore.QByteArray

Here's a full demo:

from PySide6.QtWidgets import QApplication
from PySide6.QtSvgWidgets import QSvgWidget
from PySide6.QtCore import QByteArray
import sys

svg_string="""<svg width="50" height="50">
    <circle cx="25" cy="25" r="20"/>
</svg>"""
svg_bytes = QByteArray(svg_string)
app = QApplication(sys.argv)
svgWidget = QSvgWidget()
svgWidget.renderer().load(svg_bytes)
svgWidget.show()
sys.exit(app.exec_())
0
Janosch On

The answer from @user2314737 us correct, however does not work exactly in PySide2. Below are the changes that make it work also in PySide2

from PySide2.QtCore import QByteArray
from PySide2 import QtSvg
svg_string="""<svg width="50" height="50">
    <circle cx="25" cy="25" r="20"/>
</svg>"""
svg_bytes = QByteArray(bytes(svg_string,"utf-8"))
svgWidget = QtSvg.QSvgWidget()
svgWidget.renderer().load(svg_bytes)