Canvas Paint

    The colors are stored in an array and the paint color. When one the user clicks in one of the squares the color of the square is assigned to the paintColor property of the row named colorTools.

    1. Canvas {
    2. id: canvas
    3. anchors {
    4. left: parent.left
    5. right: parent.right
    6. top: colorTools.bottom
    7. bottom: parent.bottom
    8. margins: 8
    9. }
    10. property real lastX
    11. property real lastY
    12. onPaint: {
    13. var ctx = getContext('2d')
    14. ctx.lineWidth = 1.5
    15. ctx.strokeStyle = canvas.color
    16. ctx.beginPath()
    17. ctx.moveTo(lastX, lastY)
    18. lastX = area.mouseX
    19. lastY = area.mouseY
    20. ctx.lineTo(lastX, lastY)
    21. ctx.stroke()
    22. MouseArea {
    23. id: area
    24. onPressed: {
    25. canvas.lastX = mouseX
    26. canvas.lastY = mouseY
    27. }
    28. onPositionChanged: {
    29. canvas.requestPaint()
    30. }
    31. }

    A mouse press stores the initial mouse position into the lastX and lastY properties. Every change on the mouse position triggers a paint request on the canvas, which will result in calling the onPaint handler.