Issue
I am using PySide to load an svg image into a Qt gui. The svg, made with inkscape, is composed by layers and elements (rect
, circle
, path
, g
groups...).
This is the code I am using:
from PySide import QtSvg
from PySide.QtCore import QLocale
from PySide.QtGui import *
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
svgWidget = QtSvg.QSvgWidget('file.svg')
svgWidget.show()
sys.exit(app.exec_())
Once imported, is it possible to access and edit/modify a specific node or element, for example to modify a path or to change the color of a rectangle?
Solution
Since SVG is a XML file, you can open it with QDomDocument
and edit it.
An example to change the color of the first path:
if __name__ == "__main__":
doc = QDomDocument("doc")
file = QFile("image.svg")
if not file.open(QIODevice.ReadOnly):
print("Cannot open the file")
exit(-1)
if not doc.setContent(file):
print("Cannot parse the content");
file.close()
exit(-1)
file.close()
roots = doc.elementsByTagName("svg")
if roots.size() < 1:
print("Cannot find root")
exit(-1)
# Change the color of the first path
root = roots.at(0).toElement()
path = root.firstChild().toElement()
path.setAttribute("fill", "#FF0000")
app = QApplication(sys.argv)
svgWidget = QtSvg.QSvgWidget()
svgWidget.load(doc.toByteArray())
svgWidget.show()
sys.exit(app.exec_())
Answered By - Dimitry Ernot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.