QCustomPlot的使用之二

版权声明:本文为博主原创文章,未经同意不允许转载! https://blog.csdn.net/wb175208/article/details/86618580

之前介绍过基于QT的绘图控件QCustomPlot的强大功能,详见我之前的文章Qt中关于绘图表QCustomPlot的使用
今天突然翻出来,熟悉了一下,顺便写了个Demo做为记录。

  1. QCustomPlot采用图层的方式绘制图像,通过addGraph()添加图层信息,然年后通过graph(int)获取添加的图层,然后在这个图层上进行绘制。可以添加多个图层;
  2. legend作为图例,会自动的把各个图层绘制信息添加出来,用户只需要通过graph(0)->setName设置各个绘制示例的名称;
  3. xAxis,yAxis作为坐标轴绘制显示。

1.新建一个类,继承自QCustomPlot:

#pragma once

#include "QCustomPlot.h"

class User2QCustomPlot : public QCustomPlot {
	Q_OBJECT

public:
	User2QCustomPlot(QWidget *parent);
	~User2QCustomPlot();

	void init();
};
#include "User2QCustomPlot.h"

User2QCustomPlot::User2QCustomPlot(QWidget *parent)
	: QCustomPlot(parent) {
	init();
}

User2QCustomPlot::~User2QCustomPlot() {
}

void User2QCustomPlot::init() {
	//设置可以通过鼠标拖动和滚轴缩放
	setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

	
	//设置X坐标轴
	xAxis->setVisible(true);
	xAxis->setLabel(QStringLiteral("X轴"));
	xAxis->setRange(0, 100);

	//设置Y坐标轴
	yAxis->setVisible(true);
	yAxis->setLabel(QStringLiteral("Y轴"));
	yAxis->setRange(0, 100);

	//添加图层
	addGraph();
	graph()->setPen(QPen(QColor(255, 0, 255)));
	graph()->setLineStyle(QCPGraph::LineStyle::lsLine);

	QVector<double> xValue, yValue;
	for (int i = 50; i < 200; i++) {
		xValue.push_back(i*0.1);
		yValue.push_back(i*0.5);
	}
	graph()->setData(xValue, yValue);
	graph()->setBrush(QBrush(QColor(0, 255, 0)));

	//添加图层2
	addGraph();
	graph(1)->setPen(QPen(QColor(0, 0, 255)));
	graph(1)->setLineStyle(QCPGraph::LineStyle::lsLine);

	QVector<double> xValue2, yValue2;
	for (int i = 0; i < 100; i++) {
		xValue2.push_back(100 - i);
		yValue2.push_back(i);
	}
	graph(1)->setData(xValue2, yValue2);

	//显示图例
	legend->setVisible(true);
	graph(0)->setName(QStringLiteral("测试一"));
	graph(1)->setName(QStringLiteral("测试二"));
}

2.布局UI

在界面上添加一个QWidget,然后[提升为…]User2QCustomPlot
在这里插入图片描述

3.运行结果:

在这里插入图片描述
aaa

猜你喜欢

转载自blog.csdn.net/wb175208/article/details/86618580
今日推荐