pro文件,添加一行
QT += charts
#-------------------------------------------------
#
# Project created by QtCreator 2024-08-05T07:43:10
#
#-------------------------------------------------
QT += core gui
QT += charts
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = simplechart2
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as 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 you use 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 \
mychart.cpp
HEADERS += \
mainwindow.h \
mychart.h
FORMS += \
mainwindow.ui
h文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QChartView>
#include <QLineSeries>
#include <QValueAxis>
#include <QtMath>
QT_CHARTS_USE_NAMESPACE
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QLineSeries *seriesS=nullptr;
QLineSeries *seriesC=nullptr;
QChart* chart=nullptr;
QChartView* cview=nullptr;
QValueAxis* axisX=nullptr;
QValueAxis* axisY=nullptr;
};
#endif // MAINWINDOW_H
c++文件
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// 设置主窗口的标题
setWindowTitle("simple chart");
cview=new QChartView(this);
chart=new QChart();
chart->setTitle("chart");// 设置图表的标题
cview->setChart(chart);//设置QChart为QChartView对象的图表,以便QChartView 能够显示并渲染QChart中的内容
setCentralWidget(cview);//设置cview为主窗口的中央部件,占据主要显示位置
seriesS=new QLineSeries;// 创建一个 QLineSeries 对象,用于存储和显示数据系列
chart->addSeries(seriesS);// 将数据系列添加到图表中
seriesS->setName("sin0");// 设置数据系列的名称
seriesC=new QLineSeries;//配置第二条曲线
chart->addSeries(seriesC);
seriesC->setName("cos0");
//添加数据点到序列中
qreal y0,y1,t=0,intv=0.1;
size_t count=100;
for(size_t i=0;i<count;i++)
{
y0=qSin(t);
y1=qCos(t);
seriesS->append(t,y0);
seriesC->append(t,y1);
t+=intv;
}
//设置坐标轴
axisX=new QValueAxis;
axisX->setRange(0,10);// 设置 X 轴的范围
chart->setAxisX(axisX,seriesS);// 将 X 轴添加到图表中,并关联到 seriesS
chart->setAxisX(axisX,seriesC);
axisY=new QValueAxis;
axisY->setRange(-1,1);// 设置 Y 轴的范围
chart->setAxisY(axisY,seriesS);// 将 Y 轴添加到图表中,并关联到 seriesS
chart->setAxisY(axisY,seriesC);
}
MainWindow::~MainWindow()
{
delete ui;
}