我将一个SVG图像添加到我的Qt布局中
mySvg = QtSvg.QSvgWidget('/path/to/hello.svg')
layout.addWidget(mySvg)渲染的SVG的颜色是黑色。我怎样才能改变这一点?
发布于 2020-04-20 16:47:52
也许有一种更好的解决方案,但我是通过python标准模块xml.etree.ElementTree直接编辑xml/svg内容来实现的。我不知道svg规范,但在我的例子中,我想要更改颜色的路径具有标签path。可能必须更改其他文件的标记。使用第二种方法,您可以将svg作为QByteArray获取,您可以直接将其移交到QSvgWidget中。
在我的例子中,需要对svg内容进行一些其他修改-使用这种方法非常灵活。也许将QSvgWidget子类化以集成此功能(更)有意义。
import xml.etree.ElementTree as Et
from PyQt5.QtCore import Qt, QByteArray
from PyQt5.QtGui import QColor
class Icon:
def __init__(self, icon_path, color=Qt.white):
self.tree = Et.parse(icon_path)
self.root = self.tree.getroot()
self._change_path_color(color)
def _change_path_color(self, color):
c = QColor(color)
paths = self.root.findall('.//{*}path')
for path in paths:
path.set('fill', c.name())
def get_QByteArray(self):
xmlstr = Et.tostring(self.root, encoding='utf8', method='xml')
return QByteArray(xmlstr)编辑: xpath (.//{*}path)中的*-通配符是Python3.8中的一个新特性。对于prev。必须在xpath中指定命名空间的版本:
self.namespace = root.tag.split('}')[0].strip('{')
...
paths = self.root.findall(f'.//{{{self.namespace}}}path')https://stackoverflow.com/questions/57025918
复制相似问题