How to change opacity of a SVG using Qt
-
I have an SVG which is internally represented as :
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M8 16h8V8H8v8zm12 24h8v-8h-8v8zM8 40h8v-8H8v8zm0-12h8v-8H8v8zm12 0h8v-8h-8v8zM32 8v8h8V8h-8zm-12 8h8V8h-8v8zm12 12h8v-8h-8v8zm0 12h8v-8h-8v8z" fill="rgb(255,0,0)" fill-opacity="1"/></svg>
I want to change the fill-opacity field to 0.5 . After changing the fill-opacity field i want to save the SVG . How can i do that using Qt , can we do this using QSvgRenderer ?
-
@Sougata1996 If you want to edit the SVG file directly you can use https://doc.qt.io/qt-5/qtxml-module.html as SVG is XML.
-
Thanks @jsulm , i am thinking if there is a way to set the opacity while creating an SVG . I am using QSVGGenerator to generate the SVG's ?
-
@Sougata1996 Take a look at https://forum.qt.io/topic/14762/solved-problem-with-svg-pictures-and-transparent-background/4
You should do a transparent fill at the beginning of the drawing. -
Hi
If you want to change the actual file and save it back, you could use this
https://stackoverflow.com/questions/15123544/change-the-color-of-an-svg-in-qt -
Thanks @mrjj , @jsulm : Actually what i want is any of the two :
- Just change the "fill-opacity" field of the original SVG(16x16.svg) from 1 to 0.5 and save it as a new file(16x16-disabled.svg) . OR
- Construct a completely new SVG file named as (16x16-disabled.svg) with the "fill-opacity" field having a value of 0.5 instead of the default value of 1 .
Will need some more help here ....
-
@Sougata1996
Hi
Option 1 would be possible with the code from the link.
just need to change
SetAttrRecur(doc.documentElement(), "path", "fill-opacity", "0.5"); -
Thanks @mrjj ,@jsulm , @SGaist :
QSvgGenerator svgGenerator; svgGenerator.setTitle(""); svgGenerator.setFileName(QString::fromStdWString(path.wstring())); QPainter painter(&svgGenerator); // will use this method to set the back-ground color of the SVG draw(painter); painter.save(); painter.end();
If I use option1 , i will have to edit the xml to change the "fill-opacity" field after saving the original SVG file . Can something be done to change the "fill-opacity" field during SVG creation that is before save . Here i am wanting to know if option 2 referred above is possible ?
-
Unless you are generating the original in the same way, going with the xml change will likely be faster and simpler.