Tuesday, November 27, 2012

Drawing lines in QML

QML is very nice way to build stuff, but it does lack some features that has bugged at least myself quite a lot. There is no Line element for drawing arbitrary lines from point x1,y1 to x2,y2.

Fortunately there is the Rectangle element. And what is a rectangle with a height of 1 ? More or less a line. Rectangles can be set to be at x1,y1 and you can specify the rotation. And that gives us a line from x1,y1 with a rotation. And digging deep in your brain for some basic math gives us a line drawing algorithm.

Just calculate the length from x1,y1 to x2,y2 and that gives us the width of the rectangle. Then calculate the slope and we have the rotation we need.


And here you have a Line element ready to go for your QtQuick project, free to use so enjoy!
(Note: This is a workaround for having no canvas like element in Qt 4.7/8, if you are using Qt 5 then you can use the Canvas)

import QtQuick 1.1

Rectangle {
    id: l
    property alias x1: l.x
    property alias y1: l.y

    property real x2: l.x
    property real y2: l.y

    color: "black"
    height: 2
    smooth: true;

    transformOrigin: Item.TopLeft;

    width: getWidth(x1,y1,x2,y2);
    rotation: getSlope(x1,y1,x2,y2);

    function getWidth(sx1,sy1,sx2,sy2)
    {
        var w=Math.sqrt(Math.pow((sx2-sx1),2)+Math.pow((sy2-sy1),2));
        console.debug("W: "+w);
        return w;
    }

    function getSlope(sx1,sy1,sx2,sy2)
    {
        var a,m,d;
        var b=sx2-sx1;
        if (b===0)
            return 0;
        a=sy2-sy1;
        m=a/b;
        d=Math.atan(m)*180/Math.PI;

        console.debug(a)
        console.debug(b)

        if (a<0 a="" b="" d="" else="" if="" return="">=0 && b>=0)
            return d;
        else if (a<0 b="">=0)
            return d;
        else if (a>=0 && b<0 0="" d="" else="" pre="" return="">

2 comments:

Onion said...

Sigh, seems blogger has fucked up the code a bit.

Rohit said...

can I get complete code for it?