Change the color of an svg in qt

This is how you can do it in Qt, don´t forget to add the xml and svg modules to your qt project (*.pro file). This code snippet changes the color by modifying the "fill" attribute of any "path" element but you could use it to modify any attribute of any element.

void SetAttrRecur(QDomElement &elem, QString strtagname, QString strattr, QString strattrval);

void ChangeSVGColor()
{

    // open svg resource load contents to qbytearray
    QFile file("myfile.svg");
    file.open(QIODevice::ReadOnly);
    QByteArray baData = file.readAll();
    // load svg contents to xml document and edit contents
    QDomDocument doc;
    doc.setContent(baData);
    // recurivelly change color
    SetAttrRecur(doc.documentElement(), "path", "fill", "white");
    // create svg renderer with edited contents
    QSvgRenderer svgRenderer(doc.toByteArray());
    // create pixmap target (could be a QImage)
    QPixmap pix(svgRenderer.defaultSize());
    pix.fill(Qt::transparent);
    // create painter to act over pixmap
    QPainter pixPainter(&pix);
    // use renderer to render over painter which paints on pixmap
    svgRenderer.render(&pixPainter);
    QIcon myicon(pix);
    // Use icon ....    

}


void SetAttrRecur(QDomElement &elem, QString strtagname, QString strattr, QString strattrval)
{
    // if it has the tagname then overwritte desired attribute
    if (elem.tagName().compare(strtagname) == 0)
    {
        elem.setAttribute(strattr, strattrval);
    }
    // loop all children
    for (int i = 0; i < elem.childNodes().count(); i++)
    {
        if (!elem.childNodes().at(i).isElement())
        {
            continue;
        }
        SetAttrRecur(elem.childNodes().at(i).toElement(), strtagname, strattr, strattrval);
    }
}

Since the SVG format is XML based, and XML is just ASCII text... you could load the SVG resource in to a QString, call QString::replace("\"#000000\"", "\"#ffffff\""), and then pass the modified QString in to your QSVGRenderer.


As long as you don't need it on Mac, this should work:

http://doc-snapshot.qt-project.org/4.8/qwidget.html#setGraphicsEffect

http://doc-snapshot.qt-project.org/4.8/qgraphicscolorizeeffect.html

EDIT: Or if you need to support Mac, do the svg rendering and effects inside a QGraphicsView.

http://doc-snapshot.qt-project.org/4.8/qgraphicsitem.html#setGraphicsEffect

Setup your colorize effect to color it white, and set it to the svgWidget.

Hope that helps.

Tags:

C++

Svg

Qt