Get mouse coordinates in QChartView's axis system

可紊 提交于 2019-11-28 12:16:46

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;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!