QT chart (temperature curve actual combat)


Preface

This article will start with learning about QT charts. Later we will complete a small project, a dynamic temperature curve, and transplant this project to the ARM development board to use DHT11 to detect temperature and humidity in real time.

1. Introduction to QChart

QT's QChart is a QT library for drawing various types of charts. It provides a wealth of chart types and drawing tools, and can easily draw various types of charts such as statistical charts, line charts, and pie charts. QChart is built on QT's Graphics View framework, so its bottom layer is a graphics component that integrates various rendering and layout functions.

QChart is mainly composed of the following modules:

QChart class: used to manage and draw elements such as chart data, series, and coordinate axes. It also provides some methods for setting chart style and interaction, such as setting legend, title, background color, etc.

QAbstractSeries class: An abstract class used to represent chart data series in QChart. You can create your own data series by inheriting it and implementing the corresponding functions. Subclasses include QLineSeries, QScatterSeries, QBarSeries, etc.

QAbstractAxis class: An abstract class used to represent coordinate axes. Qt supports four coordinate axes by default: x-axis, y-axis, x2-axis and y2-axis. You can create your own coordinate axes by inheriting it and implementing the corresponding functions. Subclasses include QValueAxis, QCategoryAxis, QLogValueAxis, etc.

QChartView class: used to display the view of QChart. It is a class inherited from QGraphicsView and provides some methods related to interaction and style, such as setting zoom, setting drag, etc.

The use of QChart is very flexible. Charts can be designed directly through the qtcreator tool, or charts can be drawn dynamically through code. By setting data series, axes and styles, you can easily create a variety of charts, and you can use interactive methods to make user interaction more friendly.

2. Help documentation

We can also view the corresponding usage of QChart in the help documentation in QT.

Insert image description here

3. QGraphicsView

QGraphics View is a drawing framework in QT used to create 2D graphical interfaces. It is based on QT's Graphics View framework and provides some graphics operation functions, such as scaling, translation, rotation, etc., and also provides some convenience for processing graphics. method of relationships between elements.

In QGraphics View, the interface is composed of various GraphicsItems. GraphicsItem is an abstract class that can derive various types of items. The items provided in QGraphics View include: QGraphicsPixmapItem, QGraphicsTextItem, QGraphicsEllipseItem, QGraphicsRectItem, etc. Various operations can be performed on these items, such as specifying position, size, color, etc.

QGraphics View also provides many drawing-related classes, such as QGraphicsScene, QGraphicsView, QGraphicsItemGroup, etc. Among them, QGraphicsScene is the scene class, which is responsible for managing all graphic elements and can also be regarded as a container. QGraphicsView is the view of the scene and provides some GUI-related operations, such as dragging, mouse zooming, etc.

QGraphics View also supports multi-layer overlay of scenes, that is, a scene can contain multiple layers, and each layer can manage its own items. This design makes QGraphics View more flexible and convenient when implementing complex interfaces.

QGraphicsView can also be viewed in QT Designer
Insert image description here

4. Display of QChart

To display QChart, you need to use QChartView.
QChartView is based on QT's GraphicsView framework, which provides some functions related to displaying graphics views, such as zooming, translation, rotation, etc., and also provides methods to conveniently handle the relationship between graphic elements.

By setting the QChart object to QChartView, we can display QChart data and elements in QChartView.

Realize dynamic temperature and humidity curve chart:

TempHum.h:

#ifndef TEMPHUM_H
#define TEMPHUM_H

#include <QWidget>
#include <QLineSeries>
#include <QDateTimeAxis>
#include <QTimer>
#include <QSplineSeries>

namespace Ui {
    
    
class TempHum;
}

class TempHum : public QWidget
{
    
    
    Q_OBJECT

    QLineSeries *temp_series;
    QLineSeries *hum_series;
    QDateTimeAxis *ax;
    QVector<QPointF> temperatureData;
    QTimer *timer;

    void TempChart();
    void HumChart();

public:
    explicit TempHum(QWidget *parent = nullptr);
    ~TempHum();

private:
    Ui::TempHum *ui;

private slots:
    void updateTemp();
    void on_stop_btn_clicked();
    void on_start_btn_clicked();
    void on_Exitbtn_clicked();
};

#endif // TEMPHUM_H

TempHum.cpp:

#include "TempHum.h"
#include "ui_TempHum.h"
#include <QValueAxis>
#include <QDateTime>
#include <QDebug>


TempHum::TempHum(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TempHum)
{
    
    
    ui->setupUi(this);

    /*显示温度湿度曲线*/
    TempChart();

    timer = new QTimer(this);
    timer->start(1000);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateTemp()));
}

void TempHum::TempChart()
{
    
    
    QChart * chart = new QChart();

    chart->setTitle("温度(°C)/湿度(%)");/*设置图例标题*/
    ui->Temp->setRenderHint(QPainter::Antialiasing, true);/*抗锯齿*/
    ui->Temp->setChart(chart);

    /*x轴*/
    ax = new QDateTimeAxis();
    ax->setTitleText("times");
    ax->setTickCount(15);
    ax->setLineVisible(true);
    ax->setGridLineVisible(true);
    ax->setFormat("hh:mm:ss");
    ax->setRange(QDateTime::currentDateTime(), QDateTime::currentDateTime().addSecs(15));

    /*y轴*/
    QValueAxis *ay = new QValueAxis();
    ay->setTitleText("template/humidity");
    ay->setTickCount(15);
    ay->setLabelFormat("%.1f");//让y轴显示出小数部分
    ay->setRange(0, 100);
    ay->setLineVisible(true);
    ay->setGridLineVisible(true);


    /*温度曲线*/
    temp_series = new QLineSeries();
    temp_series->setName("温度");
    temp_series->setColor(QColor(255, 200, 20));
    /*设置初始值*/
    temp_series->append(QDateTime::currentDateTime().toMSecsSinceEpoch(), 30);

    /*湿度曲线*/
    hum_series = new QLineSeries();
    hum_series->setName("湿度");
    hum_series->setColor(QColor(150, 100, 200));
    /*设置初始值*/
    hum_series->append(QDateTime::currentDateTime().toMSecsSinceEpoch(), 50);

    /*将温度曲线添加进chart*/
    chart->addSeries(temp_series);
    chart->setAxisX(ax, temp_series);
    chart->setAxisY(ay, temp_series);

    /*将湿度曲线添加进chart*/
    chart->addSeries(hum_series);
    chart->setAxisX(ax, hum_series);
    chart->setAxisY(ay, hum_series);


    //chart->legend()->hide();//隐藏图标
}


void TempHum::updateTemp()
{
    
    
    // 更新温度曲线数据
    qint64 timestamp = QDateTime::currentDateTime().toMSecsSinceEpoch();
    double temperature = (double)(rand() % 30);

    // 更新湿度数据
    double hum = (double)(rand() % 100);

    /*显示当前温度和湿度*/
    QString TempHum = QString("当前温度:") +QString::number(temperature, 'f', 1) + "°C"
                    + QString("当前湿度:") + QString::number(hum, 'f', 1) + "%";

    ui->TempHumlbl->setText(TempHum);

    /*添加当前时间点的温度和湿度*/
    if (temp_series != nullptr && hum_series != nullptr)
    {
    
    
        temp_series->append(timestamp, temperature);
        hum_series->append(timestamp, hum);
        qDebug() << temp_series->count();
        if (temp_series->count() > 16)
        {
    
    
            /*移除第一个点*/
            temp_series->removePoints(0, 1);

            hum_series->removePoints(0, 1);

        }

        qDebug() << temp_series->count();

        // 调整温度曲线的 x 轴范围
        if (temp_series->count() > 15)
        {
    
    
            ax->setRange(QDateTime::fromMSecsSinceEpoch(temp_series->at(0).x()),
                         QDateTime::fromMSecsSinceEpoch(temp_series->at(temp_series->count()-1).x()));
        }
    }
}



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

void TempHum::on_stop_btn_clicked()
{
    
    
    timer->stop();
}


void TempHum::on_start_btn_clicked()
{
    
    
    timer->start(1000);
}


void TempHum::on_Exitbtn_clicked()
{
    
    
    this->close();
}


running result:

Insert image description here

Summarize

This article will explain it here.

The source code is available on the WeChat public account.

Guess you like

Origin blog.csdn.net/m0_49476241/article/details/133063060