引言
Qt绘图(Qt Charts
)基于Qt的Graphics View
架构,其核心组件是QChartView
和 QChart
QChartView
是显示图标的视图,基类为QGraphicsView
QChart
的基类是QGraphicsltem
可以看作是视图和数据分离,即ViewModel
QChartView
QChartView
是一个独立的小部件,继承于 QGraphicsView
类。它可以直接在用户界面中显示图表。这使得在应用程序中集成图表变得简单,而无需复杂的图形场景设置。
QChart
QChart
是继承于QGraphicsWidget
,可以在QGraphicsScene
上显示,用来管理图表中的数据、图例、坐标轴等。
示例
// .h
#ifndef __WIDGET_H__
#define __WIDGET_H__
#include <QtWidgets/QWidget>
class Widget : public QWidget
{
public:
Widget();
~Widget();
public:
void createLineSeries(const std::pair<QString, std::vector<int>>& pair);
private:
class Impl;
std::unique_ptr<Impl> impl_;
};
#endif // __WIDGET_H__
// .cpp
#include "Widget.h"
#include <QtCharts/QLineSeries>
#include <QtCharts/QChartView>
#include <QtCharts/QChart>
#include <QtCharts/QValueAxis>
#include <QVBoxLayout>
#include <algorithm>
#include <vector>
QT_CHARTS_USE_NAMESPACE
class Widget::Impl
{
public:
Impl();
~Impl() = default;
public:
QChart *chart_ = nullptr;
};
Widget::Widget()
:QWidget(),
impl_(std::make_unique<Impl>())
{
setFixedSize(1700, 800);
setWindowTitle(u8"亮度对比折线图");
//创建图表框架
QVBoxLayout *lay = new QVBoxLayout;
setLayout(lay);
impl_->chart_ = new QChart();
impl_->chart_->legend()->setAlignment(Qt::AlignRight);
QChartView *charView = new QChartView(this);
charView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
charView->setChart(impl_->chart_);
lay->addWidget(charView);
}
Widget::~Widget()
{
}
void Widget::createLineSeries(const std::pair<QString, std::vector<int>> &pair)
{
QLineSeries *series = new QLineSeries();
series->setName(pair.first);
for (int i = 0, sz = pair.second.size(); i < sz; i++)
{
series->append(i, pair.second[i]);
}
impl_->chart_->addSeries(series);
//impl_->chart_->createDefaultAxes();
QValueAxis *axisY = new QValueAxis;
axisY->setRange(50, 200);
axisY->setTitleText(u8"像素值");
axisY->setLabelFormat("%i");
impl_->chart_->addAxis(axisY, Qt::AlignLeft);
QValueAxis *axisX = new QValueAxis;
axisX->setRange(0, pair.second.size());
axisX->setTitleText(u8"序号");
axisX->setLabelFormat("%i");
impl_->chart_->addAxis(axisX, Qt::AlignBottom);
series->attachAxis(axisX);
series->attachAxis(axisY);
auto allAxisX = impl_->chart_->axes(Qt::Horizontal);
auto allAxisY = impl_->chart_->axes(Qt::Vertical);
for (const auto it : allAxisX)
{
it->hide();
}
for (const auto it : allAxisY)
{
it->hide();
}
(*allAxisX.begin())->show();
(*allAxisY.begin())->show();
update();
}
Widget::Impl::Impl()
{
}