2

I am trying to make a timer in qml using the canvas API(the same one which is used in html5).I need to redraw the screen every second or so.Is there any function which could update the screen with newly fed parameters? For example I am using the arc function where I specify the angle for the clock arc to be drawn:

ctx.arc(150, 150, 95, 0,1.57,false);

In this,the angle will change every second or so.

TheBootroo
  • 7,408
  • 2
  • 31
  • 43
Parth Mody
  • 75
  • 3
  • 8

2 Answers2

6

You can't use setTimeout() in QML, it's only in JS for browsers, in Qml you must think declarative :

import QtQuick 2.0

Canvas {
    id: canvas;
    width: 360;
    height: 360;
    contextType: "2d";
    renderStrategy: Canvas.Threaded;
    renderTarget: Canvas.Image;
    antialiasing: true;
    smooth: true;

    onPaint: {
        if (context) {
            context.clearRect (0, 0, width, height);
            context.beginPath ();
            context.moveTo (width / 2, height / 2);
            context.arc (width / 2,
                         height / 2,
                         50,
                         0,
                         angle * Math.PI / 180,
                         false);
            context.closePath ();
            context.fillStyle = "red";
            context.fill ();
        }
    }

    property real angle : 0;

    Timer {
        interval: 1000;
        repeat: true;
        running: true;
        onTriggered: {
            // update your angle property as you want
            canvas.angle = (canvas.angle < 360 ? canvas.angle +6 : 0);
            // repaint
            canvas.requestPaint ();
        }
    }

}

I took the liberty to set the best settings for Canvas to allow you to have the best possible rendering !

TheBootroo
  • 7,408
  • 2
  • 31
  • 43
  • Is using a Timer the only way to force a repaint of a canvas component? Is it possible for the canvas to automatically know to repaint when a condition changes, such as data it is fed or touch input? – johnbakers Jul 24 '13 at 10:06
  • @OpenLearner you can totally add properties for each value you need in your canvas, and add onYourPropertyChanged: { canvas.requestPaint(); } – TheBootroo Jul 24 '13 at 13:30
0

You could use a setTimeOut?

setTimeout(update, 1000);

function update() {
    ctx.clearRect(0, 0, width, height);
    ctx.arc(150, 150, 95, 0,1.57,false);
}

If you need to pass the variables in, you'll need to use an anonymous function which is explained here in this post: How can I pass a parameter to a setTimeout() callback? or see code sample below.

setTimeout(function() {
    update(topicId);
}, 1000)
Community
  • 1
  • 1
Jarrod
  • 9,349
  • 5
  • 58
  • 73