在PyQt窗口中显示SVG图像的简单方法 [英] Simple way to display SVG image in a PyQt window
问题描述
我正在寻找一种在PyQt窗口中插入SVG图像的简单可靠的方法.更确切地说,我想知道是否可以将SVG图像应用于QLabel.可以对PNG图片执行此操作(请参见下面的代码).
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_())
为了调整大小,我需要保留SVG图像的矢量外观.因此,在显示之前将图像转换为PNG并没有帮助.
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.
推荐答案
QLabel
仅可以加载像素图.如果需要矢量图形,请使用QtSvg.QSvgWidget()
并加载svg文件而不进行转换:
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_())
或直接由QtSvg.QSvgRenderer
渲染为QPaintDevice
的任何子类,例如到QLabel
:
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_())
这篇关于在PyQt窗口中显示SVG图像的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!