Qt 利用QChart生成实时动态曲线

首先在.pro文件添加 QT += charts

.pro文件

QT       += core gui
QT       += charts

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    mainwindow.cpp

HEADERS += \
    mainwindow.h

FORMS += \
    mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

头文件里要注意一定要添加命名空间这句:QT_CHARTS_USE_NAMESPACE

.h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
#include 
#include 
#include 
#include 		
#include "QDateTime"

QT_CHARTS_USE_NAMESPACE   //使用QChart必须要添加这句

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

    void initDraw();                            //初始化画布


private slots:
    void on_pushButton_clicked();

    void DrawLine();                            //画线(这里可以考虑使用函数数组)

private:
    Ui::MainWindow *ui;

    QTimer *timer;                           //计时器
    QChart *chart;                           //画布
    QSplineSeries *series;                     //线
    QDateTimeAxis *axisX;                    //轴
    QValueAxis *axisY;
};
#endif // MAINWINDOW_H

main.cpp

这里面没有改动

#include "mainwindow.h"

#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    timer = new QTimer(this);                                        //创建定时器
    connect(timer,SIGNAL(timeout()),this,SLOT(DrawLine()));         //连接定时器与定时溢出处理槽函数
}

MainWindow::~MainWindow()
{
    delete ui;
}

//初始化画布
void MainWindow::initDraw()
{
    QPen penY(Qt::darkBlue,3,Qt::SolidLine,Qt::RoundCap,Qt::RoundJoin);
    chart = new QChart();
    series = new QSplineSeries;
    axisX = new QDateTimeAxis();
    axisY = new QValueAxis();

    chart->legend()->hide();                             //隐藏图例
    chart->addSeries(series);                            //把线添加到chart
    axisX->setTickCount(10);                             //设置坐标轴格数
    axisY->setTickCount(5);
    axisX->setFormat("hh:mm:ss");                        //设置时间显示格式
    axisY->setMin(0);                                    //设置Y轴范围
    axisY->setMax(10);
    axisX->setTitleText("实时时间");                       //设置X轴名称
    axisY->setLinePenColor(QColor(Qt::darkBlue));        //设置坐标轴颜色样式
    axisY->setGridLineColor(QColor(Qt::darkBlue));
    axisY->setGridLineVisible(false);                    //设置Y轴网格不显示
    axisY->setLinePen(penY);
    axisX->setLinePen(penY);

    chart->addAxis(axisX,Qt::AlignBottom);               //设置坐标轴位于chart中的位置
    chart->addAxis(axisY,Qt::AlignLeft);

    series->attachAxis(axisX);                           //把数据添加到坐标轴上
    series->attachAxis(axisY);

    axisY->setTitleText("y1");

    //把chart显示到窗口上
    ui->widget->setChart(chart);
    ui->widget->setRenderHint(QPainter::Antialiasing);   //设置抗锯齿
}

//画数据、动态更新数据
void MainWindow::DrawLine()
{
    int number;
    QDateTime currentTime = QDateTime::currentDateTime();
    //设置坐标轴显示范围
    chart->axisX()->setMin(QDateTime::currentDateTime().addSecs(-60 * 1));       //系统当前时间的前一秒
    chart->axisX()->setMax(QDateTime::currentDateTime().addSecs(0));            //系统当前时间

    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));                          //这里生成随机数做测试
    number = qrand() % 9;
    //增加新的点到曲线末端
    series->append(currentTime.toMSecsSinceEpoch(), number);
}

void MainWindow::on_pushButton_clicked()
{
    initDraw();
    timer->start();
    timer->setInterval(1000);    //设置定时周期
}

mainwindow.ui

界面只放了一个widget控件和一个button控件。button控件主要控制定时器开始。

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QChartView" name="widget" native="true">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>10</y>
      <width>781</width>
      <height>481</height>
     </rect>
    </property>
   </widget>
   <widget class="QPushButton" name="pushButton">
    <property name="geometry">
     <rect>
      <x>340</x>
      <y>520</y>
      <width>75</width>
      <height>23</height>
     </rect>
    </property>
    <property name="font">
     <font>
      <family>Arial</family>
      <pointsize>12</pointsize>
     </font>
    </property>
    <property name="text">
     <string>计时开始</string>
    </property>
   </widget>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>800</width>
     <height>22</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <customwidgets>
  <customwidget>
   <class>QChartView</class>
   <extends>QWidget</extends>
   <header location="global">qchartview.h</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>

效果图

Qt 利用QChart生成实时动态曲线_第1张图片

提示:

添加的widget控件不能显示chart图表,需要将其提升为QchartView。
具体操作:拖一个widget控件到界面,右键widget->提升为, 在提升的类名称一栏填:QChartView,头文件可以不管,会自动生成(如下图),然后确定完成。

Qt 利用QChart生成实时动态曲线_第2张图片

点击此处下载完整源码

你可能感兴趣的:(Qt)