Nixmd
Nixmd

Reputation: 845

Draw SVG using QML

How can I draw a SVG using qml in simple words?

According to QtDocs it is possible to draw a SVG using this code:

Path {
    startX: 50; startY: 50
    PathSvg { path: "L 150 50 L 100 150 z" }
}

But actually it doesn't. So, how can I draw SVG?

Upvotes: 4

Views: 4052

Answers (3)

Stephen Quan
Stephen Quan

Reputation: 25946

Let's look at different ways for drawing this shape.svg in QML.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 150">
<path fill="orange" stroke="transparent" d="M 50 50 L 150 50 L 100 150 z" />
  1. Using Image + file uri or http uri
    Image {
        source: "shape.svg"
    }
  • pro: easy to maintain
  • con: difficult to recolor
  1. Using Button + file uri
    Button {
        background: Item { }
        icon.source: "shape.svg"
        icon.width: 200
        icon.height: 150
        icon.color: "orange"
    }
  • pro: easy to maintain and recolor
  • con: svg will be recolor in a mono-color
  1. Shape + ShapePath + PathSvg:
    Shape {
        width: 200
        height: 150
        ShapePath {
            fillColor: "orange"
            strokeWidth: 0
            strokeColor: "transparent"
            startX: 50; startY: 50
            PathSvg { path: "L 150 50 L 100 150 z" }
        }
    }  
  • pro: easy to maintain and recolor
  • con: no longer looks like a svg
  1. Image + data uri
    Image {
        source: `data:image/svg+xml;utf8,
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 150">
<path fill="orange" stroke="transparent" d="M 50 50 L 150 50 L 100 150 z" />
</svg>`
    }
  • pro: allows for dynamic creation of SVG
  • con: hard to read and maintain

Upvotes: 2

If you want to show a path, you must use it within a Shape:

Shape {
    ShapePath {
        fillColor: "red"
        strokeWidth: 2
        strokeColor: "blue"
        startX: 50; startY: 50
        PathSvg { path: "L 150 50 L 100 150 z" }
    }
}

Upvotes: 9

dtech
dtech

Reputation: 49289

Nothing in the documentation says anything about drawing. It says "defines a path" by using SVG path syntax.

Drawing it is a different step:

Canvas {
    width: 400; height: 200
    contextType: "2d"

    onPaint: {
        context.strokeStyle = Qt.rgba(.4,.6,.8)
        context.path = yourPath
        context.stroke()
    }
}

Note that as long as Qt is compiled with SVG support you can directly use .svg files as image sources.

Upvotes: 4

Related Questions