1. 程式人生 > >QLineSeries繪製動態曲線

QLineSeries繪製動態曲線

  本文QLineSeries繪製動態曲線涉及到兩種,一種是曲線動態座標固定,一種是曲線和座標都是動態的。

一、曲線動態座標固定

  效果圖:
這裡寫圖片描述
這種比較簡單,直接計算座標位置,x軸超出範圍之後重新計算儲存的點地資料,替換掉超出範圍之前的所有的點的資料。

二、曲線和座標都是動態的

  效果圖:
這裡寫圖片描述
需要注意的是在QChart的addSeries之後,QLineSeries 的append之後如果資料超過座標範圍,需要手動設定xy軸範圍才能正確顯示。

原始碼:
mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: QList<QPointF> m_data; int m_count; qreal m_maxY; qreal m_minY; }; #endif
// MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include <QPushButton>
#include <QLayout>
#include <QtCharts>
#include <QTimer>
#include <math.h>
#include <QDebug>

QT_CHARTS_USE_NAMESPACE

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    m_count(0
), m_maxY(0.1), m_minY(-0.1) { QTimer *pTimer1 = new QTimer(this); QTimer *pTimer2 = new QTimer(this); QLineSeries *pSeries = new QLineSeries(); QChart *chart = new QChart(); chart->legend()->hide(); chart->addSeries(pSeries); chart->createDefaultAxes(); chart->setTitle("動態曲線圖"); QChartView *chartView = new QChartView(chart); chartView->setRenderHint(QPainter::Antialiasing); QPushButton *pBtn1 = new QPushButton(("動態曲線,座標軸固定"), this); QPushButton *pBtn2 = new QPushButton(("動態曲線,動態座標軸"), this); QWidget *pCentralWidget = new QWidget(this); QHBoxLayout *pHLayout = new QHBoxLayout(); pHLayout->addWidget(pBtn1); pHLayout->addWidget(pBtn2); pHLayout->addStretch(); QVBoxLayout *pVLayout = new QVBoxLayout(pCentralWidget); pVLayout->addLayout(pHLayout); pVLayout->addWidget(chartView); setCentralWidget(pCentralWidget); resize(800, 600); connect(pBtn1, &QPushButton::clicked, [=]() { pSeries->clear(); m_data.clear(); m_count = 0; chart->axisX()->setRange(0, 720); chart->axisY()->setRange(-1, 1); pTimer2->stop(); pTimer1->start(5); for (int i = 0; i < 720; i++) { qreal x = i; m_data.append(QPointF(i, qSin(2.0 * 3.141592 * x / 360.0))); } pSeries->append(m_data); }); connect(pBtn2, &QPushButton::clicked, [=]() { pSeries->clear(); pTimer1->stop(); m_count = 0; m_maxY = 0; m_minY = 0; chart->axisX()->setRange(0, 1); chart->axisY()->setRange(0, 1); pTimer2->start(5); }); connect(pTimer1, &QTimer::timeout, [=]() { qreal x = m_count; for (int i=0; i<m_data.size(); ++i) m_data[i].setX(m_data.at(i).x() - 1); m_data.append(QPointF(720, qSin(2.0 * 3.141592 * x / 360.0))); m_data.removeFirst(); pSeries->replace(m_data); ++ m_count; if (m_count > 360) m_count = 0; }); connect(pTimer2, &QTimer::timeout, [=]() { qreal x = m_count; QPointF point = QPointF(m_count, qSin(2.0 * 3.141592 * x / 360.0)); m_maxY = (m_maxY<point.y()) ? point.y() : m_maxY; m_minY = (m_minY>point.y()) ? point.y() : m_minY; chart->axisX()->setRange(0, point.x()); chart->axisY()->setRange(m_minY, m_maxY); pSeries->append(point); ++ m_count; }); } MainWindow::~MainWindow() { }