QT 实现曲线的动态绘制 完整类
时间: 2023-08-16 21:09:59 浏览: 162
以下是一个基于QT的曲线动态绘制的完整类,包含了一些常用的曲线绘制函数和动画效果。
```cpp
#include <QWidget>
#include <QTimer>
#include <QPainter>
#include <QVector>
class CurveWidget : public QWidget
{
Q_OBJECT
public:
CurveWidget(QWidget *parent = 0);
~CurveWidget();
void setCurveData(const QVector<QPointF> &data);
public slots:
void startAnimation();
protected:
void paintEvent(QPaintEvent *event);
private:
QVector<QPointF> m_curveData;
QTimer *m_timer;
int m_offset;
};
CurveWidget::CurveWidget(QWidget *parent)
: QWidget(parent)
{
m_timer = new QTimer(this);
m_offset = 0;
connect(m_timer, SIGNAL(timeout()), this, SLOT(update()));
}
CurveWidget::~CurveWidget()
{
}
void CurveWidget::setCurveData(const QVector<QPointF> &data)
{
m_curveData = data;
update();
}
void CurveWidget::startAnimation()
{
m_timer->start(50);
}
void CurveWidget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
// 绘制坐标系
painter.drawLine(20, height() - 20, width() - 20, height() - 20);
painter.drawLine(20, 20, 20, height() - 20);
// 绘制曲线
QPolygonF polygon;
for (int i = 0; i < m_curveData.size(); ++i) {
QPointF point(m_curveData.at(i).x() + m_offset, m_curveData.at(i).y());
if (i == 0) {
polygon << QPointF(20, height() - 20);
polygon << point;
} else {
QPointF p1 = polygon.at(i);
QPointF p2 = point;
QPointF c1((p1.x() + p2.x()) / 2, p1.y());
QPointF c2(c1.x(), p2.y());
polygon << c1 << c2 << p2;
}
}
if (polygon.size() > 1) {
painter.drawPolyline(polygon);
}
// 更新偏移量
m_offset += 1;
if (m_offset > width() - 40) {
m_offset = 0;
}
}
```
使用方法:
1. 创建一个 CurveWidget 对象,并将其添加到窗口中。
2. 调用 setCurveData 函数设置曲线数据。
3. 调用 startAnimation 函数启动动画效果。
示例:
```cpp
QVector<QPointF> data;
data << QPointF(0, 100) << QPointF(50, 200) << QPointF(100, 150)
<< QPointF(150, 250) << QPointF(200, 200) << QPointF(250, 300)
<< QPointF(300, 250) << QPointF(350, 350) << QPointF(400, 300);
CurveWidget *curveWidget = new CurveWidget(this);
curveWidget->setCurveData(data);
curveWidget->startAnimation();
```
阅读全文