qt图标系列二
qt图表一 :splinechart
效果图:
接着上篇文章的代码,我想把QLineSeries加到上个图例中,新建一个类继承QChartView
思路如下:
-
QChart *chart = new QChart(); 用于管理QLineSeries,坐标轴及图例
-
创建坐标轴:
QValueAxis* mAxY = new QValueAxis();
并设置mAxY->setRange(0, 10);//y轴范围 mAxY->setTickCount(11); // Y轴分等份 mAxY->setTitleText(QString(tr("ReadRate(%)")));//设置提示 绑定坐标轴: chart->addAxis(mAxY, Qt::AlignLeft);
-
创建QLineSeries:
QLineSeries* mLineSeries = new QLineSeries();
chart->addSeries(mLineSeries);// 将系列添加到图表
mLineSeries->attachAxis(mAxY);//绑定坐标轴
//添加点
for(int i = 0 ;i < 10;i++){
mLineSeries->append(i+1, i);
}
具体代码如下
oneline.h
#ifndef ONELINE_H
#define ONELINE_H
#include <QtCharts/QtCharts>
QT_CHARTS_USE_NAMESPACE
#include <QWidget>
class OneLine : public QChartView
{
public:
OneLine();
};
#endif // ONELINE_H
oneline.cpp
#include "oneline.h"
#include <QtCharts/QChartView>
QT_CHARTS_USE_NAMESPACE
OneLine::OneLine()
{
QChart *chart = new QChart();
//设置坐标轴
QValueAxis* mAxY = new QValueAxis();
QValueAxis* mAxX = new QValueAxis();
QLineSeries* mLineSeries = new QLineSeries();
mAxY->setRange(0, 10);//y轴范围
mAxY->setTickCount(11); // Y轴分等份
mAxX->setRange(0,10);
mAxX->setTickCount(11);
// 将系列添加到图表
chart->addSeries(mLineSeries);
chart->setTheme(QtCharts::QChart::ChartThemeBrownSand);
mAxX->setTitleText(QString(tr("ImageNumber")));
mAxY->setTitleText(QString(tr("ReadRate(%)")));
chart->addAxis(mAxY, Qt::AlignLeft);
chart->addAxis(mAxX, Qt::AlignBottom);
mLineSeries->attachAxis(mAxY);
mLineSeries->attachAxis(mAxX);
//隐藏背景
chart->setBackgroundVisible(false);
//设置外边界全部为0
chart->setContentsMargins(0, 0, 0, 0);
//设置内边界全部为0
chart->setMargins(QMargins(0, 0, 0, 0));
//设置背景区域无圆角
chart->setBackgroundRoundness(0);
//突出曲线上的点
mLineSeries->setPointsVisible(true);
//图例
QLegend *mlegend = chart->legend();
mLineSeries->setName("testname");
mLineSeries->setColor(QColor(255,0,0));
//在底部显示
mlegend->setAlignment(Qt::AlignBottom);
mlegend->show();
// 将图表绑定到视图 wiget 为 QChartView
this->setChart(chart);
for(int i = 0 ;i < 10;i++){
mLineSeries->append(i+1, i);
}
}
最后在主页面代码添加
OneLine* oneline=new OneLine();
baseLayout->addWidget(oneline, 2, 0);
编译运行成功: