Search code examples
c++qtqtcharts

Qt Charts - How to display a specific point value on x and y axis?


I have a chart with QLineSeries and I would like to display x and y value of the point where the mouse is. I think I can handle the problem of retrieving the mouse point but I don't know how to display it with Qt Charts.

I don't see functions to do that in QValueAxis and others.

The point doesn't have to be displayed on axis necessarily, directly under the mouse would be enough as well.


Solution

  • I found out a way to do it without too much drawing involved :

    void StatisticsChartView::mouseMoveEvent(QMouseEvent * event)
    {
        /* Setting the mouse position label on the axis from value to position */
        qreal x = (event->pos()).x();
        qreal y = (event->pos()).y();
    
        qreal xVal = _chart->mapToValue(event->pos()).x();
        qreal yVal = _chart->mapToValue(event->pos()).y();
    
        qreal maxX = axisX->max();
        qreal minX = axisX->min();
        qreal maxY = axisY->max();
        qreal minY = axisY->min();
    
        if (xVal <= maxX && xVal >= minX && yVal <= maxY && yVal >= minY)
        {
            QPointF xPosOnAxis = _chart->mapToPosition(QPointF(x, 0));
            QPointF yPosOnAxis = _chart->mapToPosition(QPointF(0, y));
    
            /* m_coordX and m_coordY are `QGraphicsSimpleTextItem` */
            m_coordX->setPos(x, xPosOnAxis.y() + 5);
            m_coordY->setPos(yPosOnAxis.x() - 27, y);
    
            /* Displaying value of the mouse on the label */
            m_coordX->setText(QString("%1").arg(xVal, 4, 'f', 1, '0'));
            m_coordY->setText(QString("%1").arg(yVal, 4, 'f', 1, '0'));
        }
    
        QGraphicsView::mouseMoveEvent(event);
    }
    

    It will display values along both axis