QCustomPlot绘制动态曲线,鼠标悬停显示数据
时间: 2024-05-12 22:14:00 浏览: 86
要实现动态曲线的绘制和鼠标悬停显示数据,可以使用QCustomPlot库。
首先,创建一个QCustomPlot对象,并设置x轴和y轴的范围:
```cpp
QCustomPlot *plot = new QCustomPlot(this);
plot->xAxis->setRange(0, 10);
plot->yAxis->setRange(-1, 1);
```
然后,添加一条曲线并设置其属性:
```cpp
QCPGraph *graph = plot->addGraph();
graph->setPen(QPen(Qt::blue));
graph->setAntialiasedFill(false);
```
接下来,在定时器中不断更新曲线的数据,并调用replot()函数刷新图表:
```cpp
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, [plot, graph]() {
static double phase = 0;
QVector<double> x(101), y(101);
for (int i = 0; i < 101; ++i) {
x[i] = i / 10.0;
y[i] = qSin(x[i]*2*M_PI + phase);
}
graph->setData(x, y);
plot->replot();
phase += 0.1;
});
timer->start(50);
```
最后,实现鼠标悬停显示数据的功能,可以使用QCPItemTracer类,它可以跟踪曲线上某个点的坐标,并在鼠标悬停时显示该点的数据:
```cpp
QCPItemTracer *tracer = new QCPItemTracer(plot);
tracer->setGraph(graph);
tracer->setStyle(QCPItemTracer::tsCircle);
tracer->setPen(QPen(Qt::red));
tracer->setBrush(Qt::white);
tracer->setSize(10);
tracer->setVisible(false);
connect(plot, &QCustomPlot::mouseMove, this, [plot, tracer](QMouseEvent *event) {
QPointF pos = plot->mapToValue(event->pos());
double x = pos.x();
double y = graph->data()->value(x);
if (!qIsNaN(y)) {
tracer->setVisible(true);
tracer->setGraphKey(x);
tracer->updatePosition();
QString text = QString("x=%1, y=%2").arg(x).arg(y);
QToolTip::showText(event->globalPos(), text, plot);
} else {
tracer->setVisible(false);
QToolTip::hideText();
}
});
```
完整的示例代码如下:
```cpp
#include <QApplication>
#include <QMainWindow>
#include <QCustomPlot>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow window;
QCustomPlot *plot = new QCustomPlot(&window);
plot->xAxis->setRange(0, 10);
plot->yAxis->setRange(-1, 1);
QCPGraph *graph = plot->addGraph();
graph->setPen(QPen(Qt::blue));
graph->setAntialiasedFill(false);
QCPItemTracer *tracer = new QCPItemTracer(plot);
tracer->setGraph(graph);
tracer->setStyle(QCPItemTracer::tsCircle);
tracer->setPen(QPen(Qt::red));
tracer->setBrush(Qt::white);
tracer->setSize(10);
tracer->setVisible(false);
connect(plot, &QCustomPlot::mouseMove, &window, [plot, tracer](QMouseEvent *event) {
QPointF pos = plot->mapToValue(event->pos());
double x = pos.x();
double y = graph->data()->value(x);
if (!qIsNaN(y)) {
tracer->setVisible(true);
tracer->setGraphKey(x);
tracer->updatePosition();
QString text = QString("x=%1, y=%2").arg(x).arg(y);
QToolTip::showText(event->globalPos(), text, plot);
} else {
tracer->setVisible(false);
QToolTip::hideText();
}
});
QTimer *timer = new QTimer(&window);
connect(timer, &QTimer::timeout, &window, [plot, graph]() {
static double phase = 0;
QVector<double> x(101), y(101);
for (int i = 0; i < 101; ++i) {
x[i] = i / 10.0;
y[i] = qSin(x[i]*2*M_PI + phase);
}
graph->setData(x, y);
plot->replot();
phase += 0.1;
});
timer->start(50);
window.setCentralWidget(plot);
window.resize(800, 600);
window.show();
return a.exec();
}
```
阅读全文