Qt 一个简单的QChart 绘图
先上程序运行结果图:
“sample9_1QChart.h” 文件代码如下:
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_sample9_1QChart.h"
#include <QtCharts> //必须这么设置
QT_CHARTS_USE_NAMESPACE //使用宏定义
class sample9_1QChart : public QMainWindow
{
Q_OBJECT
public:
sample9_1QChart(QWidget *parent = Q_NULLPTR);
private:
Ui::sample9_1QChartClass ui;
private:
void createChart();//
};
“sample9_1QChart.cpp” 文件代码如下:
#include "sample9_1QChart.h"
//解决QT中中文显示乱码问题
#pragma execution_character_set("utf-8")
sample9_1QChart::sample9_1QChart(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
createChart();
}
//创建图表
void sample9_1QChart::createChart()
{
QChartView *chartView = new QChartView(this); //创建 ChartView
QChart *chart = new QChart(); //创建 Chart
chart->setTitle("简单函数曲线");
chartView->setChart(chart); //Chart添加到ChartView
this->setCentralWidget(chartView);
//创建曲线序列
QLineSeries *series0 = new QLineSeries();
QLineSeries *series1 = new QLineSeries();
series0->setName("Sin曲线");
series1->setName("Cos曲线");
chart->addSeries(series0); //序列添加到图表
chart->addSeries(series1);
// QPen pen;
// pen.setStyle(Qt::DotLine);//Qt::SolidLine, Qt::DashLine, Qt::DotLine, Qt::DashDotLine
// pen.setWidth(2);
// pen.setColor(Qt::red);
// series0->setPen(pen);
// pen.setStyle(Qt::SolidLine);//Qt::SolidLine, Qt::DashLine, Qt::DotLine, Qt::DashDotLine
// pen.setColor(Qt::blue);
// series1->setPen(pen);
//序列添加数值
qreal t = 0, y1, y2, intv = 0.1;
int cnt = 100;
for (int i = 0; i < cnt; i++)
{
y1 = qSin(t);//+qrand();
series0->append(t, y1);
y2 = qSin(t + 20);
series1->append(t, y2);
t += intv;
}
// chart->createDefaultAxes();
// chart->axisX()->setTitleText("time(secs)");
// chart->axisY()->setTitleText("value");
//创建坐标轴
QValueAxis *axisX = new QValueAxis; //X 轴
axisX->setRange(0, 10); //设置坐标轴范围
// axisX->setLabelFormat("%.1f"); //标签格式
// axisX->setTickCount(11); //主分隔个数
// axisX->setMinorTickCount(4);
axisX->setTitleText("time(secs)"); //标题
// axisX->setGridLineVisible(false);
QValueAxis *axisY = new QValueAxis; //Y 轴
axisY->setRange(-2, 2);
axisY->setTitleText("value");
// axisY->setTickCount(5);
// axisY->setMinorTickCount(4);
// axisY->setLabelFormat("%.2f"); //标签格式
// axisY->setGridLineVisible(false);
chart->setAxisX(axisX, series0); //为序列设置坐标轴
chart->setAxisY(axisY, series0); //
chart->setAxisX(axisX, series1); //为序列设置坐标轴
chart->setAxisY(axisY, series1); //
}
运行的时候报错,找不到 QtCharts
#include <QtCharts> //必须这么设置
QT_CHARTS_USE_NAMESPACE //使用宏定义
这两个报错
在项目名称上,右键打开项目属性,在图中以下路径添加 QtCharts 的include 配置
然后在 链接器-->输入-->附加依赖项 中添加上 “Qt5Chartsd.lib”
配置完成后,重新运行即可。
Windows下安装VS2013+Qt5.7.0构建Qt开发环境搭建及解决小番茄无法识别、自动补全Qt的问题-CSDN博客