我有一个散点图,由QXYSeries表示,并使用Qt Charts 5.7的ChartView进行查看。

我想将鼠标悬停在图上,在一定距离内“悬停”触发,而不是仅当光标直接位于某个点上方时。想象一下鼠标周围的圆圈,只要该序列中的任何一个部分位于其中,它都会触发悬停。

有没有办法得到这种行为?

最佳答案

最终,我通过创建一个从QChartView继承的类并因此覆盖mouseMoveEvent(QMouseEvent* event)来实现此行为:

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);
        }
    }
}

10-08 03:44