在程序中对图表的实现,可以利用QT中的QtCharts的类,qt中图表类已经封装的非常全面,工作中常用的图表类型基本都有封装,而且都可以直接调用。
程序中有时候也需要用图表来实现对数据的实时监控,实现图表滚动的效果。
.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
value11 = 0;
QTimer *timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(onTime()));
timer->start(1000);
series = new QLineSeries();
series->setPen(QPen(Qt::blue,2,Qt::SolidLine));
QChart *chart = new QChart();
chart->legend()->hide();
chart->addSeries(series);
chart->createDefaultAxes();
chart->axisX()->setRange(0,59);
chart->axisY()->setRange(0,10);
QCategoryAxis *axisX = new QCategoryAxis();
QCategoryAxis *axisY = new QCategoryAxis();
chart->setAxisX(axisX, series);
chart->setAxisY(axisY, series);
QChartView *chartView = new QChartView(chart);
QGridLayout *baseLayout = new QGridLayout();
baseLayout->addWidget(chartView,1,1);
ui->widget->setLayout(baseLayout);
for(int i =0;i<60;i++){
point.append(0);
}
// point<< QPointF(0, 6) << QPointF(1, 400) << QPointF(2, 20) << QPointF(3, 128) << QPointF(4, 926) << QPointF(5, 0)<<QPointF(6, 600);
// point<<QPointF(0,800);
for (int i = 0; i < 60; i++)
{
*series << QPointF(i, point.at(i));
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onTime()
{
point.insert(0, value11++);
point.removeLast();
series->clear();
for (int i = 0; i < 60; i++)
{
*series << QPointF(i, point.at(i));
}
}
.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QWidget>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <QtCharts/QCategoryAxis>
#include <QTimer>
QT_CHARTS_USE_NAMESPACE
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void onTime();
private:
Ui::MainWindow *ui;
QList<double> point;
double value11;
QLineSeries *series;
};
#endif // MAINWINDOW_H