qmlqchartview

How to zoom on chartview and click on scatter points in qml?


I want to be able to zoom in and out on the chart. For that I can use a MouseArea. But when using that I'm not able to click on scatter points anymore. How can I handle this?

Is there anyway to do zooming without using MouseArea?

import QtQuick 2.12
import QtQuick.Window 2.12
import QtCharts 2.3

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ChartView {
        id: chart
        anchors.fill: parent
        antialiasing: true
        legend.visible: false

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

        ValueAxis {
            id: axisY
            min: 0
            max: 10
        }

        ScatterSeries {
            id: scatterSeries
            name: "Scatter Data"
            axisX: axisX
            axisY: axisY
            Component.onCompleted: {
                scatterSeries.append(1, 1);
                scatterSeries.append(2, 2);
                scatterSeries.append(3, 3);
                scatterSeries.append(4, 4);
                scatterSeries.append(5, 5);
            }
            onClicked: {
                console.log("Clicked point:", point.x, point.y)
            }
        }

        MouseArea {
            id: mouseArea
            anchors.fill: parent
            drag.target: chart
            onWheel: wheelEvent => {
                const factor = wheelEvent.angleDelta.y > 0 ? 1.2 : 0.8;
                chart.zoom(factor);
            }
        }
    }
}

Solution

  • [EDIT] New answer, move MouseArea outside your ChartView, e.g.

    MouseArea {
        ChartView {
        }
    }
    

    Original answer use WheelHandler instead of MouseArea:

                /*
                MouseArea {
                    id: mouseArea
                    anchors.fill: parent
                    drag.target: chart
                    onWheel: wheelEvent => {
                        const factor = wheelEvent.angleDelta.y > 0 ? 1.2 : 0.8;
                        chart.zoom(factor);
                    }
                }
                */
    
                WheelHandler {
                    id: wheelHandler
                    onWheel: wheelEvent => {
                        const factor = wheelEvent.angleDelta.y > 0 ? 1.2 : 0.8;
                        chart.zoom(factor);
                    }
                }
    

    WheelDemo.gif