Nominate our 2022 Qt Champions!

How to paint on qml canvas on signal clicked from qt quick contols button?

  • I have example where painting on canvas in qml starts at beggining of application:
    @import QtQuick 2.0

    Canvas {
    id: root
    // canvas size
    width: 200; height: 200
    // handler to override for drawing
    onPaint: {
    // get context to draw with
    var ctx = getContext("2d")
    // setup the stroke
    ctx.lineWidth = 4
    ctx.strokeStyle = "blue"
    // setup the fill
    ctx.fillStyle = "steelblue"
    // begin a new path to draw
    // top-left start point
    // upper line
    // right line
    // bottom line
    // left line through path closing
    // fill using fill style
    // stroke using line width and stroke style

    How to run this code for painting when i click at button created in qml. It seems to be like how to connect qml signal from button and slot in qlm for painting some figure without using c++. Thank you.

  • Hi!

    Signal/slot connection in QML works like this:

    Component.onCompleted: {
    mybutton.onClicked.connect( root.requestPaint )


  • Or you could simply write:

    Button {
    text: "click"
    onClicked: root.requestPaint()

  • is "root" object created by me? and requestPaint() is slot created by me?

  • "root" is the id of the canvas in your example and requestPaint() is a slot of the Canvas component. Take a look at the "Canvas documentation": to see what requestPaint() does.


Log in to reply