一、创建项目工程

1、创建qt 工程
2、将下载的QCustomPlot源文件的.c .h文件分别添加到源文件和头文件中
3、在./pro中添加
QT += widgets printsupport
4、在Ui界面中添加一个新的widget控件
右击鼠标选择“提升为”,提升类名称输入“QCustomPlot”,点击添加,点击提升
如图所示

二、主要代码

1、.cpp文件

#include "widget.h"
#include "ui_widget.h"
#include <QVector>
#include <QString>
Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);//绘制柱状图对象minBar = new CustomBars (ui->qcustomplot->xAxis,ui->qcustomplot->yAxis);maxBar = new CustomBars (ui->qcustomplot->xAxis,ui->qcustomplot->yAxis);fossil = new CustomBars (ui->qcustomplot->xAxis,ui->qcustomplot->yAxis);initBar();
}
void Widget::initBar()
{//设置画笔颜色red, green,blue,minBar->setPen(QPen(Qt::red));maxBar->setPen(QPen(Qt::green));fossil->setPen(QPen(Qt::blue));//设置填充颜色minBar->setBrush(Qt::red);maxBar->setBrush(Qt::green);fossil->setBrush(Qt::blue);QCPBarsGroup *group = new QCPBarsGroup(ui->qcustomplot);group->setSpacingType(QCPBarsGroup::stAbsolute);  // 设置组内柱状图的间距,按像素group->setSpacing(0);     // 设置较小的间距值,这样看起来更紧凑fossil->setBarsGroup(group);maxBar->setBarsGroup(group);minBar->setBarsGroup(group);//设置大小//minBar->setBaseValue(0.5); //设置柱状图距离x轴的距离//设置柱状图的宽度minBar->setWidth(0.5);maxBar->setWidth(0.5);fossil->setWidth(0.5);//设置抗锯齿minBar->setAntialiased(false); // gives more crisp, pixel aligned bar bordersmaxBar->setAntialiased(false);fossil->setAntialiased(false);addValue();
}
void Widget::addValue()
{//设置坐标QVector<double> ticks;QVector<QString> labels;//添加元素,将拉大刻度间的间距int count = 2;for(int i =1 ;i <20;i++){if(i == count){ticks <<i;count +=2;}}count = 0;for(int i =2 ;i <30;i++){if(i == 2+count){labels << QString::number(i,10);count +=1;}}//共享指针--坐标轴的设置QSharedPointer<QCPAxisTickerText> textTicker(new QCPAxisTickerText);textTicker->addTicks(ticks, labels);ui->qcustomplot->plotLayout()->insertRow(0);//添加x轴ui->qcustomplot->xAxis->setTicker(textTicker);//设置标签的旋转ui->qcustomplot->xAxis->setTickLabelRotation(0);ui->qcustomplot->xAxis->setSubTicks(false);//设置刻度线的长度ui->qcustomplot->xAxis->setTickLength(0, 4);//设置x轴的范围ui->qcustomplot->xAxis->setRange(0,20);//分层设置ui->qcustomplot->xAxis->grid()->setVisible(false);ui->qcustomplot->yAxis->grid()->setSubGridVisible(false);ui->qcustomplot->yAxis->setSubTicks(false);//设置y轴的范围ui->qcustomplot->yAxis->setRange(0,15);QVector<double> y,y1,y2;y << 9 << 7 << 5 << 2 << 7 << 4 << 9 << 1;y1 << 1 << 9.03 << 6 << 2 << 7 << 3<< 1 << 9;y2 << 9.87 << 7 << 5 << 2 << 7.12 << 4 << 9 << 1;minBar->addData(ticks,y);maxBar->addData(ticks,y1);fossil->addData(ticks,y2);//刷新曲线ui->qcustomplot->replot();
}Widget::~Widget()
{delete ui;
}

2、custombars.cpp文件

#include "custombars.h"CustomBars::CustomBars(QCPAxis *keyAxis, QCPAxis *valueAxis): QCPBars(keyAxis, valueAxis),mTextAlignment(Qt::AlignCenter),mSpacing(5),mFont(QFont(QLatin1String("sans serif"), 12))
{}void CustomBars::setTextAlignment(Qt::Alignment alignment)
{mTextAlignment = alignment;
}void CustomBars::setSpacing(double spacing)
{mSpacing = spacing;
}void CustomBars::setFont(const QFont &font)
{mFont = font;
}void CustomBars::draw(QCPPainter *painter)
{if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; }if (mDataContainer->isEmpty()) return;//定义两个图表数据容器QCPBarsDataContainer::const_iterator visibleBegin, visibleEnd;//获取可见数据范围getVisibleDataBounds(visibleBegin, visibleEnd);// loop over and draw segments of unselected/selected data:QList<QCPDataRange> selectedSegments, unselectedSegments, allSegments;getDataSegments(selectedSegments, unselectedSegments);allSegments << unselectedSegments << selectedSegments;for (int i = 0; i < allSegments.size(); ++i){bool isSelectedSegment = i >= unselectedSegments.size();QCPBarsDataContainer::const_iterator begin = visibleBegin;QCPBarsDataContainer::const_iterator end = visibleEnd;mDataContainer->limitIteratorsToDataRange(begin, end, allSegments.at(i));if (begin == end)continue;for (QCPBarsDataContainer::const_iterator it = begin; it != end; ++it){// draw bar:if (isSelectedSegment && mSelectionDecorator){mSelectionDecorator->applyBrush(painter);mSelectionDecorator->applyPen(painter);}else{painter->setBrush(mBrush);painter->setPen(mPen);}applyDefaultAntialiasingHint(painter);QRectF barRect = getBarRect(it->key, it->value);   //自己加的  绘制矩形float ww = barRect.width();//这两个设置可以修改柱状图与Y轴的距离// barRect.setLeft(barRect.left()+ww-20);  //设置矩形的左边缘// barRect.setRight(barRect.right()+ww-20);//设置矩形的右边缘barRect.setLeft(barRect.left()+ww); barRect.setRight(barRect.right()+ww);//绘制多边形painter->drawPolygon(barRect);// 以上是拷贝的源码部分painter->drawPolygon(barRect);// 我们仅需在 painter->drawPolygon(barRect); 这行下增加以下的内容即可// 计算文字的位置//  mFont.setPointSize(6);painter->setFont(mFont);                     // 设置字体QString text  = QString::number(it->value, 'g', 2);   // 取得当前value轴的值,保留两位精度QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip | mTextAlignment, text);  // 计算文字所占用的大小if (mKeyAxis.data()->orientation() == Qt::Horizontal) {    // 当key轴为水平轴的时候if (mKeyAxis.data()->axisType() == QCPAxis::atTop)     // 上轴,移动文字到柱状图下面textRect.moveTopLeft(barRect.bottomLeft() + QPointF(0, mSpacing));else                                                   // 下轴,移动文字到柱状图上面textRect.moveBottomLeft(barRect.topLeft() - QPointF(0, mSpacing));textRect.setWidth(barRect.width());painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, text);}else {                                                  // 当key轴为竖直轴的时候if (mKeyAxis.data()->axisType() == QCPAxis::atLeft)   // 左轴,移动文字到柱状图右边textRect.moveTopLeft(barRect.topRight() + QPointF(mSpacing, 0));else                                                  // 右轴,移动文字到柱状图左边textRect.moveTopRight(barRect.topLeft() - QPointF(mSpacing, 0));textRect.setHeight(barRect.height());painter->drawText(textRect, Qt::TextDontClip | mTextAlignment, text);}}}}

3、.h文件

custombars.h

#ifndef CUSTOMBARS_H
#define CUSTOMBARS_H#include "qcustomplot.h"class CustomBars : public QCPBars
{Q_OBJECTpublic:explicit CustomBars(QCPAxis *keyAxis, QCPAxis *valueAxis);Qt::Alignment textAligment() const { return mTextAlignment; }double spacing() const { return mSpacing; }QFont font() const { return mFont; }void setTextAlignment(Qt::Alignment alignment);void setSpacing(double spacing);void setFont(const QFont &font);
protected:Qt::Alignment mTextAlignment;   // 文字对齐方式double mSpacing;                // 文字与柱状图的间距,这里按像素大小QFont mFont;                    // 文字使用的字体virtual void draw(QCPPainter *painter) Q_DECL_OVERRIDE;};#endif // CUSTOMBARS_H

widget.h

#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>
#include "custombars.h"
namespace Ui {class Widget;
}class Widget : public QWidget
{Q_OBJECTpublic:explicit Widget(QWidget *parent = 0);~Widget();private:Ui::Widget *ui;CustomBars *minBar, *maxBar, *fossil;
public:void initBar();void addValue();
};#endif // WIDGET_H

qcustomplot绘制柱状图相关推荐

  1. 【QCustomPlot】1.2 - QCustomPlot绘制静态曲线、常用函数的功能说明

    使用QCustomPlot绘制静态曲线.并对常用函数的功能进行说明. 大部分参照别人博客,以在代码工程中附上了链接. 我的学习例程仓库,GitHub:QCustomPlot 学习例程下载 绘图坐标轴布 ...

  2. 《Qt5:QCustomPlot绘制二维图表》

    QCustomPlot 官网:https://www.qcustomplot.com/ 打开QCustomPlot 官网可以看到很多绘制二维图表的例子 下载QCustomPlot资料 打开QCusto ...

  3. Python使用matplotlib绘制柱状图(bar plot)实战:水平条形图、垂直条形图、分组条形图、堆叠条形图

    Python使用matplotlib绘制柱状图(bar plot)实战:水平条形图.垂直条形图.分组条形图.堆叠条形图 目录

  4. plotly基于dataframe数据绘制柱状图(bar plot)

    plotly基于dataframe数据绘制柱状图(bar plot) # 构建仿真pandas数据: # 绘制条形图: import plotly as py # 导入plotly库并命名为py im ...

  5. cufflinks基于dataframe数据绘制柱状图(bar plot)、堆叠柱状图(stacked bar plot)

    cufflinks基于dataframe数据绘制柱状图(bar plot).堆叠柱状图(stacked bar plot) # bar plot # from chart_studio import ...

  6. 超详细的Python matplotlib 绘制柱状图

    复习回顾 Python 为数据展示提供了大量优秀的功能包,其中 matplotlib 模块可以方便绘制制作折线图.柱状图.散点图等高质量的数据包. 关于 matplotlib 模块,我们前期已经对ma ...

  7. 用python绘制柱状图标题-Python数据可视化:5种绘制柱状图表的方法(附源码)...

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理 以下文章来源于数据Magic,作者我不是小样 前言 python里面有很多优秀的可 ...

  8. python 画柱状图-python使用Plotly绘图工具绘制柱状图

    本文实例为大家分享了python使用Plotly绘图工具绘制柱状图的具体代码,供大家参考,具体内容如下 使用Plotly绘制基本的柱状图,需要用到的函数是graph_objs 中 Bar函数 通过参数 ...

  9. python画柱形图-Python绘制柱状图

    import os #输入想要存储图像的路径 os.chdir('路径') import matplotlib.pyplot as plt import numpy as np #改变绘图风格 imp ...

最新文章

  1. Office for AI | 拯救互联网人崩溃瞬间
  2. web中的各种打印方案
  3. DOM_06之定时器、事件、cookie
  4. java内存泄漏笔记
  5. 汇编语言——十六进制数据前加0规则
  6. CentOS 初体验二十二:redis常用命令:Hash
  7. java中catalina.out_如何控制Tomcat的catalina.out的大小
  8. android java反编译
  9. cimage和gdi绘图效率比较_使用MFC CImage类和GDI+ Image加载并绘制PNG图片
  10. python--单例模式
  11. 【日常】CCB网上银行“云宠物”喂食自动化脚本
  12. VS连接数据库运行后显示对象名无效
  13. 我的世界1.19.2最终优化模组推荐:这60个优化模组让你的体验更好
  14. 【MATLAB深度学习工具箱】学习笔记--体脂估计算例再分析:拟合神经网络fitnet里面的函数】
  15. java feature task同步_FetrueTask做java方法超时处理
  16. slack 开源系统_Slack团队聊天的5种开源替代品
  17. 详述 Java 语言中的格式化输出
  18. Unity 背景图片自适应Text长度
  19. 【opencv】Camshift目标跟踪
  20. Python实现恩尼格玛加密算法——附完整源码

热门文章

  1. Linux系统的注销与关闭
  2. 【Word】长文档排版
  3. 关于表单防重复提交一些东东
  4. 电脑网页服务器拒绝连接失败,电脑服务器拒绝了连接怎么回事
  5. 人工智能-搜索----启发式搜索
  6. 服务器打不开微信怎么办,手机wifi只能用微信,打不开网页怎么处理?
  7. mysql修改字符串_mysql中replace替换字符串更改方法
  8. 神舟精盾 t97 键盘背光灯如何设置亮的时间
  9. c语言分拆素数和,分拆素数和。
  10. 傲梅的分区助手助我轻松扩C盘