Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to display SVG image in a PyQt window

Tags:

python

svg

pyqt

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.

like image 391
Roger Hache Avatar asked Feb 01 '16 11:02

Roger Hache


People also ask

How do I display svgs?

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.

Can browser display SVG?

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.

What programs can view SVG files?

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.

Can svgs have images?

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.


1 Answers

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

like image 97
a_manthey_67 Avatar answered Sep 20 '22 15:09

a_manthey_67