Nominate our 2022 Qt Champions!

[SOLVED] Problem with Canvas loading pictures

  • Hello!

    I have written the following code:

    import QtQuick 2.0

    Rectangle {
    width: 360
    height: 360

    Canvas {
        id: canvas
        property string path: ""
        anchors.fill: parent
        renderStrategy: Canvas.Immediate
        MouseArea {
            anchors.fill: parent
            onClicked: {
                canvas.path == "/home/user/1.png" ? canvas.path = "/home/user/2.png" : canvas.path = "/home/user/1.png"
        onImageLoaded: {
            var context = getContext("2d")
            context.clearRect(0, 0, canvas.width, canvas.height)
            context.drawImage(canvas.path,  0, 0);


    Clicking for the first time shows 1.png. Clicking for the second time shows 2.png. When I click for the third time 1.png is not shown. How can I achieve that?

    Best regards,

  • I guess that the loadImage will not load the image again if already loaded.
    Meaning that when you call loadImage on the third click the call to loadImage(...1.png) will not trigger onImageLoaded.
    You could use the isImageLoaded call in the onClick to check if it needs loading, if already loaded you can call the drawImage directly.

  • Your are right.
    I have inserted the following line between line 16 and 17:
    @ canvas.unloadImage(canvas.path)@

    Now it works.

Log in to reply