# Drawing lines in QML

This article explains how to draw lines using the Qt Quick Rectangle element

Tested with
SDK: Qt SDK

Compatibility
Platform(s): Qt

Article
Keywords: QML QtQuick
Created: oniongarlic (13 Dec 2012)
Last edited: hamishwillee (18 Mar 2013)

## Introduction

QML is an excellent way to describe your UI, but unfortunately it does lack an 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 ? Rectangles can be set to be at x1,y1 with a specific rotation. And that gives us a line from x1,y1 with a rotation or slope. And there you have it, a line drawing algorithm straight from school. 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.

## Line.qml

`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;         if (a<0 && b<0)            return d+180;        else if (a>=0 && b>=0)            return d;        else if (a<0 && b>=0)            return d;        else if (a>=0 && b<0)            return d+180;        else            return 0;    }}`