赞
踩
有时需要在图表中使用鼠标动态的显示某个点的数据值,Series中提供了一些相关鼠标事件的信号,此文就记录使用hovered(point point, bool state)信号实现十字交叉定位。效果图:
hovered(point point, bool state)信号发出当前鼠标所处的图表坐标Point(x,y),x和y分别代表了Series中该点处的值。借助ChartView中的函数mapToPosition(point value, AbstractSeries series)可返回得到当前鼠标于ChartView的相对位置绘制一纵一横两条交叉线。
如果像我的效果图中那样显示的十字线仅仅只在图表区域内显示,那么可以使用chartview中的属性plotArea获得绘图区域的位置大小即可。
数据结果在ToolTip中进行显示(注意:ToolTip的parent必须为Item,因此ToolTip在ChartView中初始化或者在Series中对其指定父类),以下代码只贴出了重要的核心内容,并非QML全部,其余内容可自行添加。
- ToolTip{
- id:toolTip
- delay: 4
- font.family: "微软雅黑"
- font.bold: true
- font.pointSize: 13
- }
-
- LineSeries {
- id:lineSeries
- name: "LineSeries"
- axisX: myDateTimeAxis
- axisY:myAxisY
- color: "#00ffff"
- width: 3
- onHovered: {
- var chartPosition = chartView.mapToPosition(point,lineSeries)
- myCanvas.xx = chartPosition.x
- myCanvas.yy = chartPosition.y
- toolTip.visible = state
- toolTip.text = "X:"+point.x+" Y:"+point.y
- toolTip.x = chartPosition.x+10
- toolTip.y = chartPosition.y-40
- var d = new Date()
- myCanvas.requestPaint()
- }
- }
-
- Canvas{
- id:myCanvas
- anchors.fill: chartView
- property double xx: 0
- property double yy: 0
- onPaint: {
- if(xx+yy>0){
- var ctx = getContext("2d")
- ctx.clearRect(0,0,parent.width,parent.height)
- ctx.strokeStyle = '#ccf48993'
- ctx.lineWidth = 3
- ctx.beginPath()
- ctx.moveTo(xx,chartView.plotArea.y)
- ctx.lineTo(xx,chartView.plotArea.height+chartView.plotArea.y)
- ctx.stroke()
- ctx.beginPath()
- ctx.moveTo(chartView.plotArea.x,yy)
- ctx.lineTo(chartView.plotArea.x+chartView.plotArea.width,yy)
- ctx.stroke()
- }
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。