如何使用 PySide 访问和编辑 svg 节点?
How access and edit svg nodes using PySide?
我正在使用 PySide 将 svg 图像加载到 Qt gui 中。由 inkscape 制作的 svg 由图层和元素组成(rect
、circle
、path
、g
组...)。
这是我使用的代码:
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_())
导入后,是否可以访问和edit/modify特定节点或元素,例如修改路径或更改矩形的颜色?
由于 SVG 是一个 XML 文件,您可以使用 QDomDocument
打开它并进行编辑。
更改第一条路径颜色的示例:
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_())
我正在使用 PySide 将 svg 图像加载到 Qt gui 中。由 inkscape 制作的 svg 由图层和元素组成(rect
、circle
、path
、g
组...)。
这是我使用的代码:
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_())
导入后,是否可以访问和edit/modify特定节点或元素,例如修改路径或更改矩形的颜色?
由于 SVG 是一个 XML 文件,您可以使用 QDomDocument
打开它并进行编辑。
更改第一条路径颜色的示例:
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_())