C++曲线图折线图Qt窗体绘图excel数据导入
曲线图可自由切换在相同布局窗口中,Excel数据导入生成曲线图,根据需要可修改为直方图,饼图,散点图等。
运行结果如下:
编辑
Qt Charts基于Qt的Graphics View架构,其核心组件是QChartView 和 QChart
QChartView是显示图标的视图,基类为QGraphicsView QChart的基类是QGraphicsltem 类的继承关系:
创建项目:.pro文件中添加:QT += charts
步骤:
第一步:安S,QT
第二步:新建项目
第三步:导入代码文件
第四步:运行
主要代码:
#include <QtCharts>
#include <iostream>
#include <qDebug>
#include <math.h>
using namespace std;
#include "MainWindow.h"
//
#include <QtCharts/QLineSeries>
#include <QtCharts/QSplineSeries>
#include <QPainter>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
//QObject::connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(drawDisplay()));
connect(ui.pushButton, &QPushButton::clicked, this, [=]()
{
/// 添加以下代码
//QLineSeries* series = new QLineSeries();
series->setPoints(true); // 设置数据点可见
*series
<< QPointF(11, 1)
<< QPointF(13, 3)
<< QPointF(17, 6)
<< QPointF(18, 3)
<< QPointF(20, 2);
chart->legend()->hide();
chart->addSeries(series);
chart->createDefaultAxes();
chart->setTitle("Simple line chart example");
ui.graphicsView->setRenderHint(QPainter::Antialiasing);
});
}
void QtChartZoomView::mouseMoveEvent(QMouseEvent *pEvent)
{
if (m_bMiddleButtonPressed)
{
QPoint oDeltaPos = pEvent->pos() - m_oPrePos;
this->chart()->scroll(-oDeltaPos.x(), oDeltaPos.y());
m_oPrePos = pEvent->pos();
}
__super::mouseMoveEvent(pEvent);
}
void QtChartZoomView::mousePressEvent(QMouseEvent *pEvent)
{
if (pEvent->button() == Qt::MiddleButton)
{
m_bMiddleButtonPressed = true;
m_oPrePos = pEvent->pos();
this->setCursor(Qt::OpenHandCursor);
}
__super::mousePressEvent(pEvent);
}
void QtChartZoomView::mouseReleaseEvent(QMouseEvent *pEvent)
{
if (pEvent->button() == Qt::MiddleButton)
{
m_bMiddleButtonPressed = false;
this->setCursor(Qt::ArrowCursor);
}
__super::mouseReleaseEvent(pEvent);
}
void QtChartZoomView::wheelEvent(QWheelEvent *pEvent)
{
qreal rVal = std::pow(0.999, pEvent->delta()); // 设置比例
// 1. 读取视图基本信息
QRectF oPlotAreaRect = this->chart()->plotArea();
QPointF oCenterPoint = oPlotAreaRect.center();
// 2. 水平调整
oPlotAreaRect.setWidth(oPlotAreaRect.width() * rVal);
// 3. 竖直调整
oPlotAreaRect.setHeight(oPlotAreaRect.height() * rVal);
// 4.1 计算视点,视点不变,围绕中心缩放
//QPointF oNewCenterPoint();
// 4.2 计算视点,让鼠标点击的位置移动到窗口中心
//QPointF oNewCenterPoint(pEvent->pos());
// 4.3 计算视点,让鼠标点击的位置尽量保持不动(等比换算,存在一点误差)
QPointF oNewCenterPoint(2 * oCenterPoint - pEvent->pos() - (oCenterPoint - pEvent->pos()) / rVal);
// 5. 设置视点
oPlotAreaRect.moveCenter();
// 6. 提交缩放调整
this->chart()->zoomIn(oPlotAreaRect);
__super::wheelEvent(pEvent);
}
运行结果如下:
编辑