1.IDE:QTCreator
2.实验:绘制曲线图表
3.记录:
4.代码
pro
QT += core gui
#加入以下代码引入charts
QT +=charts
greaterThan(QT_MAJOR_VERSION, 4): QT += widgetsCONFIG += c++17# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0SOURCES += \main.cpp \mainwindow.cppHEADERS += \mainwindow.hFORMS += \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
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>//加入以下两行代码
#include <QtCharts>
QT_CHARTS_USE_NAMESPACEQT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private:Ui::MainWindow *ui;//创建私有曲线
private:QChartView *chartview;QChart *chart;void CreateChartFunc(); //创建图表的函数
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);setWindowTitle("图表案例分析");CreateChartFunc(); //调用此函数实现图表绘制功能
}MainWindow::~MainWindow()
{delete ui;
}//创建图表函数
void MainWindow::CreateChartFunc()
{//创建图表chartview=new QChartView(this);chart=new QChart();chart->setTitle("sin()/cos()图表测试");chartview->setChart(chart); //添加chart到chartview库this->setCentralWidget(chartview);//创建曲线序列QLineSeries *series1=new QLineSeries();QLineSeries *series2=new QLineSeries();series1->setName("sin曲线");series2->setName("cos曲线");chart->addSeries(series1);chart->addSeries(series2);//通过序列添加数值qreal t=0,y1,y2,intv=0.1;for(int i=0;i<100;i++){y1=qSin(t);series1->append(t,y1);y2=qCos(t);series2->append(t,y2);t=t+intv;}//创建坐标轴QValueAxis *axisX=new QValueAxis(); //X轴axisX->setRange(0,10);axisX->setTitleText("time(secs)");QValueAxis *axisY=new QValueAxis(); //Y轴axisY->setRange(-2,2);axisY->setTitleText("values");chart->setAxisX(axisX,series1);chart->setAxisY(axisY,series1);chart->setAxisX(axisX,series2);chart->setAxisY(axisY,series2);
}