从qt5.7开始,qt将qtchart开源。以后画柱状图、折线图可以不必使用qwt之类的第三方库。下面给出一个例子。直接上代码:
pro:
#-------------------------------------------------
#
# Project created by QtCreator 2018-12-15T23:36:20
#
#-------------------------------------------------
QT += core gui charts
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = chartLine
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QChartView>
#include <QLineSeries>
#include <QValueAxis>
//必须有下面的宏:
QT_CHARTS_USE_NAMESPACE
namespace Ui {
class MainWindow;
}
#if !defined(POINT_QUANTITY)
#define POINT_QUANTITY 192
#endif
#if !defined(MAX_AMP_VALUE)
#define MAX_AMP_VALUE 255
#endif
#if !defined(MIN_AMP_VALUE)
#define MIN_AMP_VALUE 0
#endif
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QValueAxis * m_pAxsX;
QValueAxis * m_pAxsY;
QLineSeries * m_pLineData;
QChartView * m_pChartView;
QChart * m_pChart;
float m_fMaxY;
float m_fMinY;
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_pChartView = new QChartView;
m_pChart = m_pChartView->chart();
m_pLineData = new QLineSeries;
m_pLineData->setName("blue data");//命名图例
for(int k = 0; k < POINT_QUANTITY; k++)
{
m_pLineData->append(QPointF(k, k));
}
m_pChart->addSeries(m_pLineData);
m_pLineData->setColor(QColor(0,0,230));
m_pAxsX = new QValueAxis;
m_pAxsX->setRange(0, POINT_QUANTITY);
m_pAxsX->setTitleText("X");
m_pAxsY = new QValueAxis;
//注意,setRange只改变坐标轴的刻度显示,但QLineSeries的全部点都显示,不会因为setRange而截取一部分数据
m_pAxsY->setRange(MIN_AMP_VALUE, POINT_QUANTITY-1);
m_pAxsY->setTitleText("Y");
m_pChart->addAxis(m_pAxsX, Qt::AlignBottom);
m_pChart->addAxis(m_pAxsY, Qt::AlignLeft);
//m_pChart->legend()->setVisible(false);//隐藏图例
//m_pChart->legend()->setWindowTitle(QString::fromLocal8Bit("图例"));//无用
setCentralWidget(m_pChartView);
}
MainWindow::~MainWindow()
{
delete ui;
}
效果: