QCustomPlot绘制动态曲线,鼠标悬停显示坐標值
时间: 2024-04-13 22:06:56 浏览: 433
QCustomPlot是一个强大的Qt绘图库,可以用于绘制各种静态和动态图形。要在QCustomPlot中绘制动态曲线并显示鼠标悬停位置的坐标值,可以按照以下步骤进行:
1. 创建一个QCustomPlot对象,并添加一个QCPGraph对象用于绘制曲线。
2. 设置QCustomPlot对象的x轴和y轴范围。
3. 在一个定时器中更新QCPGraph对象的数据。
4. 为QCustomPlot对象添加一个QCPItemTracer对象,用于跟踪鼠标位置。
5. 在QCustomPlot对象上添加一个QCPItemText对象,用于显示鼠标悬停位置的坐标值。
6. 在QCustomPlot对象的鼠标移动事件中更新QCPItemTracer对象的位置和QCPItemText对象的内容。
以下是一个基本示例代码:
```cpp
// 创建QCustomPlot对象
QCustomPlot *customPlot = new QCustomPlot(this);
// 创建QCPGraph对象,并添加到QCustomPlot对象中
QCPGraph *graph = customPlot->addGraph();
graph->setPen(QPen(Qt::blue));
graph->setBrush(QBrush(QColor(0, 0, 255, 20)));
// 设置x轴和y轴范围
customPlot->xAxis->setRange(0, 10);
customPlot->yAxis->setRange(0, 10);
// 创建QCPItemTracer对象,并添加到QCustomPlot对象中
QCPItemTracer *tracer = new QCPItemTracer(customPlot);
customPlot->addItem(tracer);
// 创建QCPItemText对象,并添加到QCustomPlot对象中
QCPItemText *textLabel = new QCPItemText(customPlot);
customPlot->addItem(textLabel);
// 设置定时器,更新QCPGraph对象的数据
QTimer timer;
connect(&timer, &QTimer::timeout, [=](){
static double t = 0;
QVector<double> x(101), y(101);
for (int i=0; i<101; ++i) {
x[i] = t + i/100.0;
y[i] = sin(x[i]);
}
graph->setData(x, y);
customPlot->replot();
t += 0.1;
});
timer.start(50);
// 在鼠标移动事件中更新QCPItemTracer对象的位置和QCPItemText对象的内容
connect(customPlot, &QCustomPlot::mouseMove, [=](QMouseEvent *event){
double x = customPlot->xAxis->pixelToCoord(event->x());
double y = customPlot->yAxis->pixelToCoord(event->y());
tracer->setGraph(graph);
tracer->setGraphKey(x);
tracer->setVisible(true);
textLabel->setText(QString("(%1, %2)").arg(x).arg(y));
textLabel->position->setCoords(event->pos());
customPlot->replot();
});
```
在上面的示例代码中,我们创建了一个QCustomPlot对象,并在其中绘制了一个动态的sin曲线。我们还添加了一个QCPItemTracer对象和一个QCPItemText对象,用于在鼠标悬停时显示坐标值。在定时器的回调函数中,我们更新QCPGraph对象的数据并重新绘制QCustomPlot对象,以实现动态曲线的效果。在鼠标移动事件中,我们更新QCPItemTracer对象的位置和QCPItemText对象的内容,并重新绘制QCustomPlot对象以显示更新后的内容。
阅读全文
相关推荐














