13

Is there a way to get mouse's coordinates on plotting area of a QChartView? Preferably in the axis units. The goal is to display mouse's coordinates while moving the mouse around on the plot so the user can measure plotted objects.

I couldn't find any built in function for this on QChartView, so I'm trying to use QChartView::mouseMoveEvent(QMouseEvent *event) to try and calculate the resulting position in the plotting area. The problem is I can't get any reference to the plot area's coordinate system. I've tried using mapToScene, mapToItem and mapToParent and also the reverse mapFrom... on all objects I can grab a hold of to try to do this, but to no avail.

I've found that QChartView::chart->childItems()[2] is indeed the plotting area, excluding the axis and axis labels. I can then call QChartView::chart->childItems()[2]->setCursor(Qt::CrossCursor) to make a cross appear only on the plotting area and not on the adjacent objects. But still, nothing I try seems to make a correct reference to this object's coordinate system.

1 Answer 1

18

QChartView is simply a QGraphicsView with an embedded scene(). To get coordinates within any of the charts, you have to go through several coordinate transformations:

  1. Start with the view widget coordinates
  2. view->mapToScene: widget (view) coordinates → scene coordinates
  3. chart->mapFromScene: scene coordinates → chart item coordinates
  4. chart->mapToValue: chart item coordinates → value in a given series.
  5. End with value coordinates in a given series.

The term "chart item" and "chart widget" are synonyms, since QChart is-a QGraphicsWidget is-a QGraphicsItem. Note that QGraphicsWidget is not a QWidget!

Implementing it like this works like a charm (thanks, Marcel!):

auto const widgetPos = event->localPos();
auto const scenePos = mapToScene(QPoint(static_cast<int>(widgetPos.x()), static_cast<int>(widgetPos.y()))); 
auto const chartItemPos = chart()->mapFromScene(scenePos); 
auto const valueGivenSeries = chart()->mapToValue(chartItemPos); 
qDebug() << "widgetPos:" << widgetPos; 
qDebug() << "scenePos:" << scenePos; 
qDebug() << "chartItemPos:" << chartItemPos; 
qDebug() << "valSeries:" << valueGivenSeries;
1
  • That seems to be the correct combination of coordinate mapping. What I ended up doing was subclassing QChartView and implementing chart()->mapToValue() within QChartView::mouseMoveEvent(), which worked right away. The subclassing was useful for implementing Zooming and Panning too.
    – A. Vieira
    Commented May 20, 2017 at 8:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.