Issue
I have a Canvas object, which onPaint method looks like this:
onPaint: {
var ctx = getContext("2d");
ctx.fillStyle = Qt.rgba(1, 1, 1, 1);
ctx.fillRect(0, 0, width, height);
}
Just fill the Canvas with white color.
After this, I want to draw a point on this Canvas when I press on some Button, can I just change the Canvas in the onClick method of the Button object? For me it looks like if I want to draw something on Canvas I need to call requestPaint(), but requestPaint() just will fill the all Canvas in white. So, I see one solution, I need to declare
property var point: [x, y]
and change the onPaint method to something like this:
onPaint: {
var ctx = getContext("2d");
ctx.fillStyle = Qt.rgba(1, 1, 1, 1);
ctx.fillRect(0, 0, width, height);
//pseudocode
if point is not empty:
ctx.fillStyle = Qt.rgba(1, 0, 0, 1);
ctx.fillRect(point.x, point.y, 1, 1)
}
Will it work? Is there a better way to do what I described? Thanks.
Solution
In general you could create a null property, and use the signal that is emited when there is a change to invoke requestPaint()
, and in onPaint()
you draw a circle that emulates the point.
import QtQuick 2.0
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.2
ApplicationWindow {
visible: true
width: 640
height: 480
property var drawPoint: null
onDrawPointChanged: canv.requestPaint()
ColumnLayout {
anchors.fill: parent
anchors.margins: 9
Button {
height: 40
Layout.fillWidth: true
text: qsTr("Random Point")
onClicked: drawPoint = Qt.point(Math.random()*canv.width ,Math.random()*canv.height);
}
Canvas {
id: canv
Layout.fillWidth: true
Layout.fillHeight: true
onPaint: {
var ctx = getContext("2d");
ctx.fillStyle = Qt.rgba(1, 1, 1, 1);
ctx.fillRect(0, 0, width, height);
if(drawPoint !== null){
ctx.beginPath();
ctx.arc(drawPoint.x, drawPoint.y, 5, 0, 2 * Math.PI);
ctx.fillStyle = Qt.rgba(1, 0, 0, 1);
ctx.fill()
ctx.strokeStyle = Qt.rgba(1, 0, 0, 1);
ctx.stroke();
}
}
}
}
}
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.