[Qt] QChart draws static graphics (take sin and cos as examples)

Qtcharts is a graphics-drawing component that comes with the high-level version of Qt.
How to use it to draw a simple line chart?
This article takes sin and cos as examples to record the drawing process.

Environmental preparation

When installing Qt5.7 and above, check the Qtcharts component at the same time . You
need to pay attention not to skip charts when configuring.

Steps for usage

1. Modify .pro

Add in .pro file

QT += charts

2. UI design steps

When drawing the ui, place a widget of type "Widget",
set the objectName to "ChartView",
then right-click on it and select "Promote to...".
First add the QChartView class. insert image description here
insert image description here
If there is still a need to upgrade later, you can right-click to 'promote to' -> select QchartView
insert image description here

3. Modify the ui header file

Add the following code to the ui header file

#include <QtCharts>
QT_CHARTS_USE_NAMESPACE

As shown below
insert image description here

4. Write the code

Create a qchart object

QChart* chart = new QChart();

Create two QLineSeries objects, use append to add data points, and setName to set the polyline title.
Take sin and cos images as an example.

    // 创建折线系列对象
    QLineSeries *series = new QLineSeries();
    QLineSeries *series2 = new QLineSeries();
    // 使用append添加数据点
    for (quint32 i = 0; i < 100; i++) {
    
    
        series->append(i, sin(0.1f*i));
        series2->append(i, cos(0.1f*i)); 
    }
    // 设置折线的标题
    series->setName("sin");
    series2->setName("cos");

A line series is added to the chart, a default axis is created, and an
icon is added to the display object.

    // 折线系列添加到图表
    chart->addSeries(series);
    chart->addSeries(series2);
    // 基于已添加到图表的 series 来创建默认的坐标轴
    chart->createDefaultAxes();  
    // chart图表添加到ChartView的对象      
    ui->ChartView->setChart(chart);

display effect

insert image description here

full code

mainwindow

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


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    
    
    ui->setupUi(this);
    QChart* chart = new QChart();
    // 创建折线系列对象
    QLineSeries *series = new QLineSeries();
    QLineSeries *series2 = new QLineSeries();
    // 使用append添加数据点
    for (quint32 i = 0; i < 100; i++) {
    
    
        series->append(i, sin(0.1f*i));
        series2->append(i, cos(0.1f*i)); //series->append(i, cos(0.6f*i));
    }
    // 设置折线的标题
    series->setName("sin");
    series2->setName("cos");
    // 折线系列添加到图表
    chart->addSeries(series);
    chart->addSeries(series2);
    // 基于已添加到图表的 series 来创建默认的坐标轴
    chart->createDefaultAxes();
    ui->ChartView->setChart(chart);
}

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

Guess you like

Origin blog.csdn.net/qq_44078824/article/details/121800688