1. 创建界面,将widget作为容器进行绘图,并将widget提升为QChartView类
1.1 单击widget,右键中选择“提升”,提升的类名称中填写“QChartView”,会自动生成头文件名,选择“添加”将类和头文件添加进要提升的类中
1.2 选择添加的类及头文件点击“提升”(此处我之前已经提升过,因此方框中已有相关选项,直接勾选对应选项选择提升即可)
1.3 提升后的效果
2. 代码准备
2.1 .pro文件
#-------------------------------------------------
#
# Project created by QtCreator 2021-07-29T16:15:22
#
#-------------------------------------------------
QT += core gui
QT += charts
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = QtInterface
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has 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
CONFIG += c++11
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
2.2 .h文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtCharts>
QT_CHARTS_USE_NAMESPACE
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
2.3 .cpp文件
#include "mainwindow.h"
#include <QtCharts>
QT_CHARTS_USE_NAMESPACE
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QChart* chart = new QChart();
QLineSeries *series = new QLineSeries();
for (quint32 i = 0; i < 100; i++) {
series->append(i, sin(0.6f*i));
}
chart->addSeries(series);
chart->createDefaultAxes(); // 基于已添加到图表的 series 来创建默认的坐标轴
ui->widget->setChart(chart);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
}
2.4 main.cpp文件保持默认即可
3. 运行结果
参考博文链接:https://blog.csdn.net/qingzhuyuxian/article/details/98032943