1

I want to draw a line at a fix position in a Canvas. I've written the following code:

function drawVLine(){
    var ctx1 = myCanvas.getContext("2d");

    ctx1.reset();
    ctx1.lineJoin = "round";

    ctx1.save()
    ctx1.lineWidth = 2
    ctx1.strokeStyle = "green"
    var x = 50
    ctx1.beginPath()
    ctx1.moveTo(x, 0)
    ctx1.lineTo(x, myCanvas.height)
    ctx1.stroke()
    ctx1.restore()
}

This code works properly when I call it from event handler onPaint but if I call this function through some other function, it does nothing. I want to execute this function on certain signal and I don't want to call myCanvas.requestPaint() to trigger onPaint event and then draw the line.

Is it the case that Context can be fetched only from onPaint event?

EDIT:

according to comments and various attempts, I came to conclusion that, Painting methods can not be used out of onPaint events.

Swanand
  • 4,027
  • 10
  • 41
  • 69
  • What problem to call this method from `onPaint`? This signal is emmited when `Canvas` has to be painted, so that exactly what you need. you can trigger rainting by `markdirty()` or `requestPaint()` – folibis Jun 29 '15 at 11:08
  • @folibis I do lot of other things in `onPaint` and I don't want to repeat them for painting this line... So, I am searching for other way – Swanand Jun 29 '15 at 11:16
  • Ma be you want to use `QQuickPaintedItem` instead of `Canvas`? So you will be able to use some cache operation etc. – folibis Jun 29 '15 at 11:22
  • 1
    I think you cannot use painting methods outside of `onPaint` just because it will be overwritten be calling `onPaint` when your `Canvas` need repaint – folibis Jun 29 '15 at 11:25
  • @folibis Yes... I also think so :-( – Swanand Jun 29 '15 at 11:29
  • 2
    That's for sure: all painting actions must occur in the painting even handler. If you exploit [`markDirty`](http://doc.qt.io/qt-5/qml-qtquick-canvas.html#markDirty-method) as suggested by @folibis you can use the passed parameter (`region`) to distinguish the specific paintings for your line from all the other paint actions. If the region is smaller than the whole canvas (it is) execute the line painting code. That is feasible depending on the current `onPaint` code, clearly. – BaCaRoZzo Jun 29 '15 at 11:59

0 Answers0