Get mouse coordinates in QChartView's axis sys

2019-01-19 19:58发布

问题:

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:

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;


标签: c++ qt qtchart