Python 在qml中是否可以重画画布对象的内容?
我有一个Canvas对象,onPaint方法如下所示:Python 在qml中是否可以重画画布对象的内容?,python,pyqt,qml,pyqt5,Python,Pyqt,Qml,Pyqt5,我有一个Canvas对象,onPaint方法如下所示: onPaint: { var ctx = getContext("2d"); ctx.fillStyle = Qt.rgba(1, 1, 1, 1); ctx.fillRect(0, 0, width, height); } onPaint: { var ctx = getContext("2d"); ctx.fillStyle = Qt.rgba(1, 1, 1, 1); ctx.fill
onPaint: {
var ctx = getContext("2d");
ctx.fillStyle = Qt.rgba(1, 1, 1, 1);
ctx.fillRect(0, 0, width, height);
}
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)
}
用白色填充画布就行了
在这之后,当我按下某个按钮时,我想在画布上画一个点,我可以在按钮对象的onClick方法中更改画布吗?对我来说,如果我想在画布上绘制一些东西,我需要调用requestPaint(),但是requestPaint()只会用白色填充整个画布。所以,我看到了一个解决方案,我需要声明
属性变量点:[x,y]
并将onPaint方法更改为如下内容:
onPaint: {
var ctx = getContext("2d");
ctx.fillStyle = Qt.rgba(1, 1, 1, 1);
ctx.fillRect(0, 0, width, height);
}
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)
}
行吗?有没有更好的方法来实现我所描述的?
谢谢。通常,您可以创建一个空属性,并使用在调用
requestPaint()
时发出的信号,然后在onPaint()
中绘制一个模拟该点的圆
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();
}
}
}
}
}