Displaying SVG on a QGraphicsView
-
I've been trying to load an SVG file into a
QGraphicsView
object. From the error messages I get, I assume I need to use aQGraphicsScene
and add my SVG to that, and then give the scene to the view. I did some searching and found aQSvgRenderer
class which I can successfully load my SVG file into, but I'm not sure how to provide this to theQGraphicsScene
.I tried this:
svg_renderer = QSvgRenderer() svg_renderer.load("assets\\key_signatures\\c_sharp.svg") scene = QGraphicsScene() scene.addItem(svg_renderer) self.ui.c_major_display.setScene(scene)
But I get errors about
QGraphicsScene
needing aQGraphicsItem
.
An old StackOverflow post I found says to use aQGraphicsWebView
like this:item = QGraphicsWebView() item.load('file.svg') view = QGraphicsView() scene = QGraphicsScene() scene.addItem(item) view.setScene(scene) view.show() sys.exit(app.exec_())
But to my knowledge, this is deprecated (it not only crashes Qt Designer, but also doesn't show up in the import list).
I also found docs on a
QGraphicsSvgItem
which explicitly states its purpose is to load SVGs into aQGraphicsView
, but I can't seem to import it in PySide6.
Any ideas? -
Update: I figured it out. I found in the changelog for Qt 6 that much of
QtSvg
has been moved intoQtSvgWidgets
. From here, I was able to do this:from PySide6.QtSvgWidgets import QGraphicsSvgItem from PySide6.QtWidgets import QGraphicsScene svg_item = QGraphicsSvgItem("assets\\key_signatures\\c.svg") scene = QGraphicsScene() scene.addItem(svg_item) my_graphics_view.setScene(scene)
-
Hi,
One note: use forward slashes for your paths. It's less error prone and Qt handles the conversion if needed.
-
Hi,
One note: use forward slashes for your paths. It's less error prone and Qt handles the conversion if needed.
@SGaist I just kind of threw it in there as a placeholder. Does Qt handle it completely, or should I still use
os.path.join
to be safe? -
Qt handles the conversion internally so you'll be fine. Currently you have a Windows specific path so not really portable.
If you want to stay in the Python land, you should use pathlib and convert the path to a string before passing it to Qt.