qt 中的qcustoomplot 添加两个游标并获取对应点的值 
时间: 2023-05-31 14:04:06 浏览: 21
在 Qt 中,可以使用 QCustomPlot 库来实现添加游标并获取对应点的值。下面是一个简单的示例代码:
```cpp
#include <QApplication>
#include <QCustomPlot/qcustomplot.h>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// 创建 QCustomPlot 对象
QCustomPlot customPlot;
// 添加一个图层
customPlot.addGraph();
// 生成示例数据
QVector<double> x(101), y(101);
for (int i = 0; i < 101; ++i)
{
x[i] = i / 5.0 - 10;
y[i] = qExp(-x[i] * x[i] * 0.01) * qCos(x[i]);
}
// 设置数据
customPlot.graph(0)->setData(x, y);
// 添加两个游标
QCPItemLine *verticalLine = new QCPItemLine(&customPlot);
QCPItemLine *horizontalLine = new QCPItemLine(&customPlot);
verticalLine->setPen(QPen(Qt::red));
horizontalLine->setPen(QPen(Qt::red));
verticalLine->setZValue(10);
horizontalLine->setZValue(10);
verticalLine->setVisible(false);
horizontalLine->setVisible(false);
// 连接鼠标移动事件,实现游标位置跟随
QObject::connect(&customPlot, &QCustomPlot::mouseMove, [&](QMouseEvent *event){
// 获取鼠标所在坐标系上的位置
QPointF pos = customPlot.mapToGraph(event->pos());
// 设置游标位置
verticalLine->start->setCoords(pos.x(), customPlot.yAxis->range().lower);
verticalLine->end->setCoords(pos.x(), customPlot.yAxis->range().upper);
horizontalLine->start->setCoords(customPlot.xAxis->range().lower, pos.y());
horizontalLine->end->setCoords(customPlot.xAxis->range().upper, pos.y());
// 显示游标
verticalLine->setVisible(true);
horizontalLine->setVisible(true);
// 获取对应点的值
double xValue = pos.x();
double yValue = customPlot.graph(0)->data()->at(customPlot.graph(0)->data()->findBegin(xValue))->value;
qDebug() << "x: " << xValue << ", y: " << yValue;
});
// 显示图形
customPlot.replot();
customPlot.show();
return app.exec();
}
```
在这个示例中,我们首先创建了一个 QCustomPlot 对象,并添加了一个图层。然后,我们生成了一些示例数据,并设置了图层的数据。接着,我们创建了两个游标,并将它们的颜色设置为红色,Z 坐标设置为 10,初始时不可见。
然后,我们连接了 QCustomPlot 的鼠标移动事件,实现游标位置随鼠标移动,并在每次移动时获取对应点的值,并打印出来。
最后,我们显示了图形,进入 Qt 的事件循环中。当鼠标移动时,游标会跟随鼠标移动,并在控制台输出对应点的值。
相关推荐
















