Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML - How to load SVG DOM into an Image

Tags:

svg

qt

qml

I have a Simple QML project working with SVG files.

here i can load image.svg from qrc resource properly.

Image {
        id: svg
        source: "svg/image.svg"
        x: 0
        y: header.height
        fillMode: Image.PreserveAspectFit
    }

I want to know is that possible to assign a DOM SVG as String to Image.source ?

the String like this:

<svg version="1.1" id="svg2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="1147.592px" height="1397.27px" viewBox="0 0 1147.592 1397.27" enable-background="new 0 0 1147.592 1397.27" xml:space="preserve"><polygon fill="none" stroke="#010101" stroke-miterlimit="10" points="839.432,179.454 839.432,190.151 
852.657,189.897 852.657,180.621 "/></svg>
like image 335
hamed Avatar asked Dec 17 '25 23:12

hamed


1 Answers

You can embed image data using data URI exactly as it could be done in HTML:

import QtQuick 2.11
import QtQuick.Window 2.2

Window {
    visible: true
    width: 200
    height: 200
    title: qsTr("Inline SVG example")

    Image {
        anchors.centerIn: parent
        source: "data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 96 105\"> <g fill=\"#97C024\" stroke=\"#97C024\" stroke-linejoin=\"round\" stroke-linecap=\"round\"> <path d=\"M14,40v24M81,40v24M38,68v24M57,68v24M28,42v31h39v-31z\" stroke-width=\"12\"/> <path d=\"M32,5l5,10M64,5l-6,10 \" stroke-width=\"2\"/> </g> <path d=\"M22,35h51v10h-51zM22,33c0-31,51-31,51,0\" fill=\"#97C024\"/> <g fill=\"#FFF\"> <circle cx=\"36\" cy=\"22\" r=\"2\"/> <circle cx=\"59\" cy=\"22\" r=\"2\"/> </g> </svg>"
    }
}

The image source could be encoded using Base64 for convenience. But I don't think it's effective way to draw SVG. You should either load SVG file or draw SVG image directly using Qt SVG.

like image 62
folibis Avatar answered Dec 21 '25 04:12

folibis