I'm looking for a simple and reliable way for inserting an SVG image in a PyQt window. More precisely, I'm wondering if it's possible to have an SVG image applied to a QLabel. This can be done for PNG images (see code bellow).
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
label = QtGui.QLabel()
pixmap = QtGui.QPixmap('my_image.png')
label.setPixmap(pixmap)
label.show()
sys.exit(app.exec_())
Edit:
I need to keep the vector aspect of the SVG image for resizing purpose. So converting the image to PNG before displaying it isn't helping.
From Chrome and Edge to Safari and Firefox, all the major browsers allow you to open SVG files these days — whether you're on a Mac or Windows. Just launch your browser and click on File > Open to choose the file you want to view. It'll then be displayed in your browser.
You can open SVG images in your browser just like webpages. So embedding an SVG document with an <iframe> is done just like we studied in From <object> to <iframe> — other embedding technologies.
Google Chrome, Firefox, IE, Opera, and every popular browser has the capacity to render SVG images. SVG files are also supported in basic text editors and high-end Graphics editors like CorelDRAW.
SVG files tend to store images more efficiently than common raster formats as long as the image is not too detailed. SVG files contain enough information to display vectors at any scale, whereas bitmaps require larger files for scaled-up versions of images — more pixels use up more file space.
QLabel
only can load a pixmap. If You need a vector-graphic use QtSvg.QSvgWidget()
and load the svg-file without converting:
import sys
from PyQt4 import QtGui, QtSvg
app = QtGui.QApplication(sys.argv)
svgWidget = QtSvg.QSvgWidget('Zeichen_123.svg')
svgWidget.setGeometry(50,50,759,668)
svgWidget.show()
sys.exit(app.exec_())
or render to any subclass of QPaintDevice
by QtSvg.QSvgRenderer
directly, e.g. to QLabel
:
app = QtGui.QApplication(sys.argv)
widget = QtGui.QLabel()
widget.setGeometry(50,200,500,500)
renderer = QtSvg.QSvgRenderer('Zeichen_123.svg')
widget.resize(renderer.defaultSize())
painter = QtGui.QPainter(widget)
painter.restore()
renderer.render(painter)
widget.show()
sys.exit(app.exec_())
get Zeichen_123.svg here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With