在qml中的qtcharts上扯了一个点

时间:2018-02-14 14:42:09

标签: qt qml qt5 qtchart

我试图在qtcharts上的LineSeries上拖一点。这是我的代码:

import QtQuick 2.0
import QtCharts 2.0

Item {
    anchors.fill: parent

    ChartView {
        title: "Two Series, Common Axes"
        anchors.fill: parent

        ValueAxis {
            id: axisX
            min: 0
            max: 10
            tickCount: 5
        }

        ValueAxis {
            id: axisY
            min: -0.5
            max: 1.5
        }

        LineSeries {
            id: series1
            axisX: axisX
            axisY: axisY
            onPressed: console.log("Pressed: " + point.x + ", " + point.y);   
            onReleased: console.log("Released: " + point.x + ", " + point.y);
        }


    }
    // Add data dynamically to the series
    Component.onCompleted: {
        for (var i = 0; i <= 10; i++) {
            series1.append(i, Math.random());
        }
    }
}

当我按下Lineserie上的一个点时,我可以看到我在控制台中按下并释放的点的x,y。两者都是相同的,所以我看不到它发布的地方。我想将一个点拖到另一个地方,所以如果我按下一个点,它会跟随(触摸屏上的鼠标/手指)指针,直到我在图表上释放。任何人都可以帮助我们从哪里开始,我应该使用哪些属性?

1 个答案:

答案 0 :(得分:2)

不幸的是,ChartViewLineSeries都没有MouseMove事件,因此很难跟踪拖动事件。我有一个使用MouseArea放置在图表上的解决方法。也许是一个愚蠢的解决方案,但至少它是有效的。我已经将它用于你的例子:

ChartView {
    id: chart
    property var selectedPoint: undefined
    title: "Two Series, Common Axes"
    anchors.fill: parent
    antialiasing: true
    property real toleranceX: 0.05
    property real toleranceY: 0.05

    ValueAxis {
        id: axisX
        min: 0
        max: 10
        tickCount: 5
    }

    ValueAxis {
        id: axisY
        min: -0.5
        max: 1.5
    }

    LineSeries {
        id: series1
        axisX: axisX
        axisY: axisY
        pointsVisible: true            
    }

    MouseArea {
        anchors.fill: parent
        onPressed:
        {
            var cp = chart.mapToValue(Qt.point(mouse.x,mouse.y));
            for(var i = 0;i < series1.count;i ++)
            {
                var p = series1.at(i);
                if(Math.abs(cp.x - p.x) <= chart.toleranceX && Math.abs(cp.y - p.y) <= chart.toleranceY)
                {
                    chart.selectedPoint = p;
                    break;
                }
            }
        }
        onPositionChanged: {
            if(chart.selectedPoint != undefined) {
                var p = Qt.point(mouse.x, mouse.y);
                var cp = chart.mapToValue(p);
                if(cp.x >= axisX.min && cp.x <= axisX.max && cp.y >= axisY.min && cp.y <= axisY.max) {
                    series1.replace(chart.selectedPoint.x, chart.selectedPoint.y, cp.x, cp.y);
                    chart.selectedPoint = cp;
                }
            }
        }

        onReleased: {
            chart.selectedPoint = undefined;
        }
    }

}
// Add data dynamically to the series
Component.onCompleted: {
    for (var i = 0; i <= 10; i++) {            
        series1.append(i, Math.random());
    }
}