用Qt绘制柱状图
最近复习已经学习的Qt知识,制作了一个简单的图表显示工具。目前它能够很好地显示柱状图,其效果如下所示:
这个柱状图支持任意多的项目(柱子),只需要在代码中添加了相关数据后,使用Paint()函数就可以将其渲染成一个Pixmap,然后作为中央控件(centeralwidget)的一张图片显示出来。下面是源代码的下载地址:这里
如果对程序的实现感兴趣,那么看看我写的相关类吧。
#ifndef HISTOGRAM_H #define HISTOGRAM_H // Histogram.h 柱状图类的声明 // 名词解释:Histogram 柱状图 // pillar 柱子 #include <QVector> // 前向声明 QT_BEGIN_NAMESPACE class QColor; class QRect; class QString; class QPaintDevice; QT_END_NAMESPACE class HistogramItem { public: QString m_Name; qreal m_Value; QColor m_PillarColor; QRect m_PillarRect; }; class Histogram { public: Histogram( void ); void AddItem( QString name, qreal value, QColor pillarColor ); void SetMaxValue( quint32 maxValue ); // 设置最大值,以便绘图 void Paint( QPaintDevice* pDevice ); // 绘图 private: void DrawAxis( QPaintDevice* pDevice, QPainter* pPainter ); void DrawPillars( QPaintDevice* pDevice, QPainter* pPainter ); // 绘制柱子 void DrawText( QPainter *pPainter ); // 绘制文字 void DrawScale( QPaintDevice* pDevice, QPainter* pPainter );