创建四个颜色盒子,然后将这四个盒子装在 Row 定位器中,Row 定位器保存一个变量,此变量保存用户通过点击这四个盒子决定的颜色值!
ColorSquare组件:
import QtQuick 2.5
Rectangle {
id: root
width: 48; height: 48
color: "green"
signal clicked
property bool active: false
border.color: active? "#666666" : "#f0f0f0"
border.width: 2
MouseArea {
id: area
anchors.fill :parent
onClicked: {
root.clicked()
}
}
}
Row {
id: colorTools
anchors {
horizontalCenter: parent.horizontalCenter
top: parent.top
topMargin: 8
}
// 画笔颜色
property color paintColor: "#33B5E5"
spacing: 4
// ---- 四个成员
Repeater {
model: ["#33B5E5", "#99CC00", "#FFBB33", "#FF4444"]
ColorSquare {
id: red
color: modelData
active: parent.paintColor == color
onClicked: {
// 盒子响应点击信号,
// 设置 parent.paintColor 的值
parent.paintColor = color
}
}
}
}
当我们点击鼠标的时候,会将鼠标的坐标保存在程序中,当移动鼠标的时候会触发 onPaint 绘制窗口(根据更新之后的鼠标位置)
原理代码:
onPaint: {
var ctx = getContext('2d')
// 线条宽度
ctx.lineWidth = 1.5
// 线条颜色
ctx.strokeStyle = canvas.color
ctx.beginPath()
// 绘制“直线”
ctx.moveTo(lastX, lastY)
lastX = area.mouseX
lastY = area.mouseY
ctx.lineTo(lastX, lastY)
ctx.stroke()
}
MouseArea {
id: area
// 鼠标区域覆盖整个画布
anchors.fill: parent
// 点击鼠标记录鼠标位置
onPressed: {
canvas.lastX = mouseX
canvas.lastY = mouseY
}
// 鼠标移动
onPositionChanged: {
canvas.requestPaint()
}
}
原理代码解析: