【问题标题】:Qt - Change the color of a QSvgWidgetQt - 改变 QSvgWidget 的颜色
【发布时间】:2019-11-23 08:09:50
【问题描述】:

我有一个 SVG 图像,我添加到我的 Qt 布局中

mySvg = QtSvg.QSvgWidget('/path/to/hello.svg')
layout.addWidget(mySvg)

渲染的 SVG 的颜色是黑色。我该如何更改?

【问题讨论】:

    标签: python qt svg pyqt


    【解决方案1】:

    可能有一个更优雅的解决方案,但我通过python标准模块xml.etree.ElementTree直接编辑xml/svg内容来实现这一点。 我不知道svg 规范,但在我的情况下,我想更改颜色的path 有标签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) 中的 *-wildcard 是 python 3.8 中的一个新功能。对于上一页。版本命名空间必须在 xpath 中指定:

    self.namespace = root.tag.split('}')[0].strip('{')
    ...
    paths = self.root.findall(f'.//{{{self.namespace}}}path')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多