QML-Canva畫板畫圖功能-跟隨鼠標位置進行隨筆畫
阿新 • • 發佈:2018-10-13
rect pac context 跟隨鼠標 left 1.4 hang int getc
參考博主文章進行整理了代碼,實現功能https://blog.csdn.net/UbuntuTouch/article/details/46375697
功能實現如下圖:
1.組件ColorSquare.qml
該組件主要是顏色提取塊,完整代碼如下:
import QtQuick 2.0 Rectangle { id: colorSquare; 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: { colorSquare.clicked() } } }
設置了該組件激活狀態為false,邊框顏色在點擊激活狀態下顏色為“#666”,就是該顏色提取塊被選中時邊框顏色改變
2.main.qml
主文件是執行畫筆功能和顏色選取,我給添加了註釋,原博主的引入文件我不知道如何在cpp中註冊的,所以進行了整改,完整代碼如下:
import QtQuick 2.7 import QtQuick.Window2.2 import QtQuick.Controls 1.4 Window{ id: root width: 640 height: 480 visible: true Row{ id:colorTools//顏色提取工具 anchors{ horizontalCenter: parent.horizontalCenter top: parent.top topMargin: 8 } property color paintColor:"#33b5e5"//設置初始畫筆顏色 spacing: 4; Repeater{//四個colorSquare model: ["#33B5E5", "#99CC00", "#FFBB33", "#FF4444"]//modelData 顏色數據 ColorSquare{ id:red; color: modelData; active: parent.paintColor == color//當選中一個colorSquare時,當前畫筆顏色為選中的顏色 onClicked: { parent.paintColor = color } } } } Rectangle{ anchors.fill: canvas border.color: "#666" border.width: 4; } Canvas{ id:canvas; anchors{ left: parent.left; right:parent.right; top:colorTools.bottom; bottom: parent.bottom; margins: 8 }
//鼠標點擊坐標位置 property real lastX property real lastY property color color: colorTools.paintColor onPaint: { var ctx = getContext("2d") ctx.lineWidtn = 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()//當鼠標press位置改變 完成當前繪制 } } } }//Window
QML-Canva畫板畫圖功能-跟隨鼠標位置進行隨筆畫