有时在QML开发中需要在chart图表中进行放大缩小,拖拽图表曲线进行查看,效果图:
ChartView中提供了四种移动图表曲线的方法:
- scrollDown(pixels)
- scrollLeft(pixels)
- scrollRight(pixels)
- scrollUp(pixels)
四种方法移动的单位均为像素,因此如果需要进行鼠标拖拽,需要进一步进行坐标转化,代码实现较简单,因此不过多论述,直接上代码段:
import QtQuick 2.0
import QtCharts 2.2
ChartView {
id:chartView
title: "XXX数据源"
antialiasing: true
backgroundColor: "#9917719b"
titleColor: "#ccffffff"
titleFont.bold: true
titleFont.family: "方正粗倩_GBK"
titleFont.pointSize: 15
MouseArea{
id:mouseArea
anchors.fill: parent
property int currentX:0
property int currentY: 0
onWheel: {//图形缩放
if(wheel.angleDelta.y>0){
chartView.zoom(1.1)
chartView.scrollRight(40)
}
else{
chartView.zoom(0.9)
}
}
onPressed: {//获取点击时位置
mouseArea.cursorShape = Qt.ClosedHandCursor
currentX = mouse.x
currentY = mouse.y
}
onReleased: {
mouseArea.cursorShape = Qt.ArrowCursorArrowCursor
}
onPositionChanged:{//拖拽功能实现
var moveX = mouse.x-currentX
var moveY = mouse.y-currentY
currentX = mouse.x
currentY = mouse.y
chartView.scrollLeft(moveX)
chartView.scrollUp(moveY)
}
}
}