折线图
#include "widget.h"
#include "ui_widget.h"
#include <QtCharts/QChart>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include<QVBoxLayout>Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);//创建一个 QChart 对象,并设置其标题为 "Sample Line Chart"。QChart *chart = new QChart();chart->setTitle("Sample Line Chart");//创建一个 QLineSeries 对象,这是用于存储折线图数据的系列。QLineSeries *series = new QLineSeries();//使用 append 方法向系列中添加数据点。这里添加了三个数据点:(0, 1),(1, 2) 和 (2, 3)。series->append(0, 1);series->append(1, 2);series->append(2, 3);//将数据系列添加到图表中chart->addSeries(series);//创建一个 QChartView 对象,它是一个视图,用于显示图表。QChartView *chartView = new QChartView(chart);//创建一个垂直布局 QVBoxLayout。QVBoxLayout *layout = new QVBoxLayout;//将图表视图添加到布局中。layout->addWidget(chartView);//将布局设置为窗口小部件的布局。this->setLayout(layout);}
饼图:
#include "widget.h"
#include "ui_widget.h"
#include <QtCharts/QChart>
#include <QtCharts/QChartView>
#include <QtCharts/QPieSeries>
#include<QVBoxLayout>Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);// 创建饼图QChart *chart = new QChart();chart->setTitle("Sample Pie Chart");// 创建饼图系列QPieSeries *series = new QPieSeries();series->append("Apples", 30); // 添加数据项和对应的值series->append("Oranges", 20);series->append("Pears", 50);// 将饼图系列添加到图表中chart->addSeries(series);// 饼图特定的设置series->setLabelsVisible(true); // 显示标签series->setHoleSize(0.2); // 设置饼图中心的空白大小// 创建图表视图QChartView *chartView = new QChartView(chart);// 创建布局并添加图表视图QVBoxLayout *layout = new QVBoxLayout;layout->addWidget(chartView);this->setLayout(layout);}Widget::~Widget()
{delete ui;
}
柱状图:
#include "widget.h"
#include "ui_widget.h"
#include <QtCharts/QChart>
#include <QtCharts/QChartView>
#include <QtCharts/QBarSeries>
#include <QtCharts/QBarSet>
#include<QVBoxLayout>Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);// 创建柱状图QChart *chart = new QChart();chart->setTitle("Sample Bar Chart");// 创建柱状图系列QBarSeries *series = new QBarSeries();// 创建不同的柱状集QBarSet *setApples = new QBarSet("Apples");setApples->append(30); // 苹果的数量QBarSet *setOranges = new QBarSet("Oranges");setOranges->append(20); // 橙子的数量QBarSet *setPears = new QBarSet("Pears");setPears->append(50); // 梨的数量// 将柱状集添加到系列中series->append(setApples);series->append(setOranges);series->append(setPears);// 将柱状图系列添加到图表中chart->addSeries(series);// 创建图表视图QChartView *chartView = new QChartView(chart);// 创建布局并添加图表视图QVBoxLayout *layout = new QVBoxLayout;layout->addWidget(chartView);this->setLayout(layout);
}Widget::~Widget()
{delete ui;
}