Search code examples
c++qtqtcharts

Qt QXYSeries and ChartView - modify hovered behavior to trigger within a range


I have a scatter plot represented by a QXYSeries and viewed with a ChartView from Qt Charts 5.7.

I want to hover my mouse over the plot, have "hovered" trigger within a certain distance, rather than only when my cursor is directly on top of a point. Imagine a circle around the mouse, that will trigger hovered whenever any part of the series is within it.

Is there a way to get this behavior?


Solution

  • Eventually, I got this behavior by creating a class that inherits from QChartView and overriding mouseMoveEvent(QMouseEvent* event) thusly:

    void ScatterView::mouseMoveEvent(QMouseEvent* event)
    {
        if(!this->chart()->axisX() || !this->chart()->axisY())
        {
            return;
        }
        QPointF inPoint;
        QPointF chartPoint;
        inPoint.setX(event->x());
        inPoint.setY(event->y());
        chartPoint = chart()->mapToValue(inPoint);
        handleMouseMoved(chartPoint);
    }
    
    void ScatterView::handleMouseMoved(const QPointF &point)
    {
        QPointF mousePoint = point;
        qreal distance(0.2); //distance from mouse to point in chart axes
        foreach (QPointF currentPoint, scatterSeries->points()) { 
            qreal currentDistance = qSqrt((currentPoint.x() - mousePoint.x())
                                          * (currentPoint.x() - mousePoint.x())
                                          + (currentPoint.y() - mousePoint.y())
                                          * (currentPoint.y() - mousePoint.y()));
            if (currentDistance < distance) {
                triggerPoint(currentPoint);
            }
        }
    }