首頁 > 軟體

QT中QChart繪製折線圖

2022-04-07 19:01:26

一、簡單繪圖

Qt Charts基於Qt的Graphics View架構,其核心元件是QChartViewQChart

  • QChartView是顯示圖示的檢視,基礎類別為QGraphicsView
  • QChart的基礎類別是QGraphicsltem

類的繼承關係:

建立專案:.pro檔案中新增:QT += charts
程式碼如下:其他檔案未修改,修改程式碼只在mainwindow.cpp檔案中進行。
mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QChartView>
#include <QLineSeries>
#include <QValueAxis>
#include <QtMath>
QT_CHARTS_USE_NAMESPACE

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("QChart簡單繪圖");

    //建立圖表框架
    QChartView* cview = new QChartView(this);
    QChart* chart = new QChart();
    chart->setTitle("簡單函數曲線");

    cview->setChart(chart);
    setCentralWidget(cview);

    //建立折現序列
    QLineSeries* seriesS = new QLineSeries;
    QLineSeries* seriesC = new QLineSeries;
    seriesS->setName("Sinθ");
    seriesC->setName("Cosθ");
    chart->addSeries(seriesS);
    chart->addSeries(seriesC);

    //新增資料繪製
    qreal y0,y1,t=0,intv=0.1;
    size_t count=100;
    for (size_t i=0;i<count;i++) {
        y0 = qSin(t);
        y1 = qCos(t);
        seriesS->append(t,y0);
        seriesC->append(t,y1);
        t += intv;
    }

    //建立座標軸
    QValueAxis* axisX = new QValueAxis;
    axisX->setRange(0,10);
    chart->setAxisX(axisX,seriesS);
    chart->setAxisX(axisX,seriesC);

    QValueAxis* axisY = new QValueAxis;
    axisY->setRange(-1, 1);
    chart->setAxisY(axisY,seriesS);
    chart->setAxisY(axisY,seriesC);

}

MainWindow::~MainWindow()
{
    delete ui;
}

二、繪製折線圖

資料序列類繼承關係

座標類繼承關係

範例

初步UI設計

自定義DialogPen類

新建DialogPen類繼承QDialog

#ifndef DIALOGPEN_H
#define DIALOGPEN_H

#include <QDialog>
#include <QColorDialog>
#include <QPen>
#include <QPalette>

namespace Ui {
class DialogPen;
}

class DialogPen : public QDialog
{
    Q_OBJECT

public:
    explicit DialogPen(QWidget *parent = nullptr);
    ~DialogPen();

    QPen getpen();
    static QPen getPen(QPen initPen, bool &ok);
    void setPen(const QPen &pen);

private slots:
    void on_pushButton_clicked();

private:
    QPen m_pen;
    Ui::DialogPen *ui;
};

#endif // DIALOGPEN_H
#include "dialogpen.h"
#include "ui_dialogpen.h"
#include <QString>


DialogPen::DialogPen(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogPen)
{
    ui->setupUi(this);
    ui->comboBox->clear();
    ui->comboBox->addItem("NoPen",0);
    ui->comboBox->addItem("SolidLine",1);
    ui->comboBox->addItem("DashLine",2);
    ui->comboBox->addItem("DotLine",3);
    ui->comboBox->addItem("DashDotLine",4);
    ui->comboBox->addItem("DashDotDotLine",5);
    ui->comboBox->addItem("CustomDashLine",6);
    ui->comboBox->setCurrentIndex(0);
}

DialogPen::~DialogPen()
{
    delete ui;
}

void DialogPen::on_pushButton_clicked()
{
    QColor color = m_pen.color();
    QColorDialog::getColor(color);
    if(color.isValid()){
        QString str = QString::asprintf("background-color: rgb(%d,%d,%d)",color.red(),color.green(),color.blue());
        ui->btnColor->setStyleSheet(str);
    }

}

QPen DialogPen::getpen()
{
    m_pen.setStyle(Qt::PenStyle(ui->comboBox->currentIndex()));
    m_pen.setWidth(ui->spinBox->value());
    QColor color = ui->btnColor->palette().color(QPalette::Button);
    m_pen.setColor(color);
    return m_pen;
}

QPen DialogPen::getPen(QPen initPen, bool &ok)
{
    DialogPen* dlg = new DialogPen;
    QPen pen;
    dlg->setPen(initPen);
    int ret = dlg->exec();
    if (ret == QDialog::Accepted){
        pen = dlg->getpen();
        ok = true;
    }else {
        pen = initPen;
        ok = false;
    }
    delete dlg;
    return pen;
}

void DialogPen::setPen(const QPen &pen)
{
    m_pen = pen;
    ui->spinBox->setValue(pen.width());
    int i = static_cast<int>(pen.style());
    ui->comboBox->setCurrentIndex(i);
    ui->btnColor->setAutoFillBackground(true);
    QColor color = pen.color();
    QString str = QString::asprintf("background-color: rgb(%d,%d,%d)",color.red(),color.green(),color.blue());
    ui->btnColor->setStyleSheet(str);
}

mainwindow類

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QChartView>
#include <QtCharts>
#include <QColor>
#include <QLineSeries>
#include <QValueAxis>
#include <QtMath>
#include <QTime>
#include <QChart>
#include <QFontDialog>
#include "dialogpen.h"

QT_CHARTS_USE_NAMESPACE

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_actZoomOut_triggered();

    void on_actZoomIn_triggered();

    void on_actReset_triggered();

    void on_actFlush_triggered();

    void on_btn_set_clicked();

    void on_btn_titleFont_clicked();

    void on_rBtn_Up_clicked();

    void on_rBtn_Down_clicked();

    void on_rBtn_Left_clicked();

    void on_rBtn_Right_clicked();

    void on_checkBox_legend_clicked(bool checked);

    void on_checkBox_legendBG_clicked(bool checked);

    void on_pBtn_Font_clicked();

    void on_pBtn_legendcolor_clicked();

    void on_pBtn_setMargin_clicked();

    void on_comboBox_motion_currentIndexChanged(int index);

    void on_comboBox_theme_currentIndexChanged(int index);

    void on_sin_curve_clicked();

    void on_cos_curve_clicked();

    void on_pBtn_name_clicked();

    void on_checkBox_curve_clicked(bool checked);

    void on_checkBox_data_clicked(bool checked);

    void on_pBtn_color_clicked();

    void on_pBtn_pen_clicked();

    void on_horizontalSlider_valueChanged(int value);

    void on_checkBox_pointLableVisible_clicked(bool checked);

    void on_pushButton_13_clicked();

    void on_pushButton_12_clicked();

    void on_rBtn_Y_clicked();

    void on_rBtn_XY_clicked();

    void on_rBtn_XAxies_clicked();

    void on_rBtn_YAxies_clicked();

    void on_Axis_isVisible_clicked(bool checked);

    void on_Axis_range_clicked();

    void on_Axis_setTitle_clicked();

    void on_Axis_titleIsVisible_clicked(bool checked);

    void on_pBtn_style_clicked();

    void on_pBtn_Fontcolor_clicked();

    void on_pBtn_setFont_clicked();

    void on_chk_scaleIsVisible_clicked(bool checked);

    void on_chk_gridLineVisible_clicked(bool checked);

    void on_pBtn_Fontcolor_2_clicked();

    void on_pBtn_Fontcolor_3_clicked();

    void on_spinBox_Tickcount_valueChanged(int arg1);

    void on_spinBox_minorTickcount_valueChanged(int arg1);

    void on_chk_TickLineIsVisible_clicked(bool checked);

    void on_pBtn_Fontcolor_5_clicked();

    void on_pBtn_Fontcolor_4_clicked();

    void on_pBtn_Fontcolor_7_clicked();

    void on_pBtn_Fontcolor_6_clicked();

    void on_chk_MinorTickLineIsVisible_clicked(bool checked);

private:
    Ui::MainWindow *ui;
    void createChart();
    QLineSeries* curSeries;
    QValueAxis* curAxis;

    void prepareData();
    void updateFromChart();
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "ui_dialogPen.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    createChart();
    prepareData();
    updateFromChart();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_actZoomOut_triggered()
{
    ui->cView->chart()->zoom(0.8);

}

void MainWindow::on_actZoomIn_triggered()
{
    ui->cView->chart()->zoom(1.2);
}

void MainWindow::on_actReset_triggered()
{
    ui->cView->chart()->zoomReset();
}

void MainWindow::createChart()
{
    QChart* chart = new QChart();
    chart->setTitle("simple curve");
    ui->cView->setChart(chart);
    ui->cView->setRenderHint(QPainter::Antialiasing);
    QLineSeries* series0 = new QLineSeries;
    QLineSeries* series1 = new QLineSeries;
    series0->setName("sin");
    series1->setName("cos");
    curSeries = series0;

    QPen pen;
    pen.setStyle(Qt::DotLine);
    pen.setWidth(2);
    series0->setPen(pen);
    pen.setStyle(Qt::SolidLine);
    pen.setColor(Qt::blue);
    series1->setPen(pen);

    chart->addSeries(series0);
    chart->addSeries(series1);

    QValueAxis* axisX = new QValueAxis;
    QValueAxis* axisY = new QValueAxis;
    curAxis = axisX;
    axisX->setRange(0,10);
    axisX->setLabelFormat("%.1f");
    axisX->setTickCount(11);
    axisX->setMinorTickCount(4);
    axisX->setTitleText("time(secs)");

    axisY->setRange(-1.5,1.5);
    axisY->setTickCount(3);
    axisY->setMinorTickCount(4);
    axisY->setTitleText("value");

    chart->setAxisX(axisX,series0);
    chart->setAxisX(axisX,series1);
    chart->setAxisY(axisY,series0);
    chart->setAxisY(axisY,series1);

}

void MainWindow::prepareData()
{
    QLineSeries* series0 = (QLineSeries*)ui->cView->chart()->series().at(0);
    QLineSeries* series1 = (QLineSeries*)ui->cView->chart()->series().at(1);
    int cnt = 100;
    series0->clear();
    series1->clear();
    qsrand(QTime::currentTime().second());
    qreal t=0, y1, y2, inv=0.1;
    qreal rd;
    for (int i=0; i<cnt; i++) {
        rd = (qrand()%10)-5;
        y1 = qSin(t) + rd/50;
        series0->append(t,y1);

        y2 = qCos(t) + rd/50;
        series1->append(t,y2);
        t += inv;
    }
}

void MainWindow::updateFromChart()
{
    QChart* chart = ui->cView->chart();
    ui->lineEdit_title->setText(chart->title());
    QMargins mg = chart->margins();
    ui->spinBox_Down->setValue(mg.bottom());
    ui->spinBox_Left->setValue(mg.left());
    ui->spinBox_Right->setValue(mg.right());
    ui->spinBox_Up->setValue(mg.top());
}




void MainWindow::on_actFlush_triggered()
{
    prepareData();
}

void MainWindow::on_btn_set_clicked()
{
    QChart *chart = ui->cView->chart();
    chart->setTitle(ui->lineEdit_title->text());
}

void MainWindow::on_btn_titleFont_clicked()
{
    QFont font = ui->cView->chart()->titleFont();
    bool ok = false;
    font = QFontDialog::getFont(&ok,font);
    if(ok)
        ui->cView->chart()->setTitleFont(font);
}

void MainWindow::on_rBtn_Up_clicked()
{
    ui->cView->chart()->legend()->setAlignment(Qt::AlignTop);
}

void MainWindow::on_rBtn_Down_clicked()
{
    ui->cView->chart()->legend()->setAlignment(Qt::AlignBottom);
}

void MainWindow::on_rBtn_Left_clicked()
{
    ui->cView->chart()->legend()->setAlignment(Qt::AlignLeft);
}

void MainWindow::on_rBtn_Right_clicked()
{
    ui->cView->chart()->legend()->setAlignment(Qt::AlignRight);
}


void MainWindow::on_checkBox_legend_clicked(bool checked)
{
    ui->cView->chart()->legend()->setVisible(checked);
}

void MainWindow::on_checkBox_legendBG_clicked(bool checked)
{
    ui->cView->chart()->legend()->setBackgroundVisible(checked);
}

void MainWindow::on_pBtn_Font_clicked()
{
    QFont font = ui->cView->chart()->legend()->font();
    bool ok = false;
    font = QFontDialog::getFont(&ok,font);
    if(ok)
        ui->cView->chart()->legend()->setFont(font);
}

void MainWindow::on_pBtn_legendcolor_clicked()
{
    QColor color = ui->cView->chart()->legend()->labelColor();
    color = QColorDialog::getColor(color);
    if(color.isValid())
        ui->cView->chart()->legend()->setLabelColor(color);
}

void MainWindow::on_pBtn_setMargin_clicked()
{
    QMargins mgs;
    mgs.setTop(ui->spinBox_Up->value());
    mgs.setLeft(ui->spinBox_Down->value());
    mgs.setLeft(ui->spinBox_Left->value());
    mgs.setRight(ui->spinBox_Right->value());
    ui->cView->chart()->setMargins(mgs);
}

void MainWindow::on_comboBox_motion_currentIndexChanged(int index)
{
    ui->cView->chart()->setAnimationOptions((QChart::AnimationOption)index);
}

void MainWindow::on_comboBox_theme_currentIndexChanged(int index)
{
    ui->cView->chart()->setTheme((QChart::ChartTheme)index);
}

void MainWindow::on_sin_curve_clicked()
{
    if(ui->sin_curve->isChecked())
        curSeries = (QLineSeries*)ui->cView->chart()->series().at(0);
    else
        curSeries = (QLineSeries*)ui->cView->chart()->series().at(1);

    //獲取curSeries的值, 設定(標題名稱,序列可見的,點資料可見,透明度滑動條)
    ui->lineEdit_title->setText(curSeries->name());
    ui->checkBox_curve->setChecked(curSeries->isVisible());
    ui->checkBox_data->setChecked(curSeries->pointsVisible());
    ui->horizontalSlider->setValue(curSeries->opacity()*10);
    ui->checkBox_pointLableVisible->setChecked(curSeries->pointLabelsVisible());
}

void MainWindow::on_cos_curve_clicked()
{
    on_sin_curve_clicked();
}

void MainWindow::on_pBtn_name_clicked()
{
    curSeries->setName(ui->line_name->text());
}



void MainWindow::on_checkBox_curve_clicked(bool checked)
{
    Q_UNUSED(checked)
    curSeries->setVisible(ui->checkBox_curve->isChecked());
}

void MainWindow::on_checkBox_data_clicked(bool checked)
{
    Q_UNUSED(checked)
    curSeries->setPointsVisible(ui->checkBox_data->isChecked());
}

void MainWindow::on_pBtn_color_clicked()
{
    QColor color = curSeries->color();
    color = QColorDialog::getColor(color);
    if(color.isValid())
        curSeries->setColor(color);
}

void MainWindow::on_pBtn_pen_clicked()
{
    bool ok = false;
    QPen pen = curSeries->pen();
    pen = DialogPen::getPen(pen, ok);
    if(ok)
        curSeries->setPen(pen);
}

void MainWindow::on_horizontalSlider_valueChanged(int value)
{
    curSeries->setOpacity(value/10.0);
}

void MainWindow::on_checkBox_pointLableVisible_clicked(bool checked)
{
    curSeries->setPointLabelsVisible(checked);
}

void MainWindow::on_pushButton_13_clicked()
{
    QColor color = curSeries->pointLabelsColor();
    color = QColorDialog::getColor(color);
    if(color.isValid())
        curSeries->setPointLabelsColor(color);
}

void MainWindow::on_pushButton_12_clicked()
{
    QFont font = curSeries->pointLabelsFont();
    bool ok = false;
    font = QFontDialog::getFont(&ok, font);
    if(ok)
        curSeries->setPointLabelsFont(font);
}

void MainWindow::on_rBtn_Y_clicked()
{
    if(ui->rBtn_Y->isChecked())
        curSeries->setPointLabelsFormat("@yPoint");
    else
        curSeries->setPointLabelsFormat("(@xPoint,@yPoint)");
}

void MainWindow::on_rBtn_XY_clicked()
{
    on_rBtn_Y_clicked();
}

void MainWindow::on_rBtn_XAxies_clicked()
{
    // 設定座標軸
    QList<QAbstractAxis*> axes;
    if(ui->rBtn_XAxies->isChecked())
        axes = ui->cView->chart()->axes(Qt::Horizontal);
    else
        axes = ui->cView->chart()->axes(Qt::Vertical);
    curAxis = (QValueAxis*)axes[0];

    //獲取座標軸屬性,顯示到介面上
    ui->dSBox_minV->setValue(curAxis->min());
    ui->dSBox_maxV->setValue(curAxis->max());

    ui->Axis_title->setText(curAxis->titleText());
    ui->Axis_titleIsVisible->setChecked(curAxis->isTitleVisible());

    ui->lineEdit_style->setText(curAxis->labelFormat());
    ui->chk_scaleIsVisible->setChecked(curAxis->labelsVisible());


    ui->chk_gridLineVisible->setChecked(curAxis->isGridLineVisible());

    ui->spinBox_Tickcount->setValue(curAxis->tickCount());
    ui->chk_TickLineIsVisible->setChecked(curAxis->isLineVisible());

    ui->spinBox_minorTickcount->setValue(curAxis->minorTickCount());
    ui->chk_MinorTickLineIsVisible->setChecked(curAxis->isMinorGridLineVisible());

}



void MainWindow::on_rBtn_YAxies_clicked()
{
    on_rBtn_XAxies_clicked();
}

void MainWindow::on_Axis_isVisible_clicked(bool checked)
{
    curAxis->setVisible(checked);
}

void MainWindow::on_Axis_range_clicked()
{
    curAxis->setRange(ui->dSBox_minV->value(), ui->dSBox_maxV->value());
}


void MainWindow::on_Axis_setTitle_clicked()
{
    curAxis->setTitleText(ui->Axis_title->text());
}

void MainWindow::on_Axis_titleIsVisible_clicked(bool checked)
{
    curAxis->setTitleVisible(checked);
}

void MainWindow::on_pBtn_style_clicked()
{
    curAxis->setLabelFormat(ui->lineEdit_style->text());
}

void MainWindow::on_pBtn_Fontcolor_clicked()
{
    QColor color = curAxis->labelsColor();
    color = QColorDialog::getColor(color);
    if(color.isValid())
        curAxis->setLabelsColor(color);
}

void MainWindow::on_pBtn_setFont_clicked()
{
    QFont font = curAxis->labelsFont();
    bool ok = false;
    font = QFontDialog::getFont(&ok, font);
    if(ok)
        curAxis->setLabelsFont(font);
}

void MainWindow::on_chk_scaleIsVisible_clicked(bool checked)
{
    curAxis->setLineVisible(checked);
}


void MainWindow::on_chk_gridLineVisible_clicked(bool checked)
{
    curAxis->setGridLineVisible(checked);
}

void MainWindow::on_pBtn_Fontcolor_2_clicked()
{
    QColor color = curAxis->gridLineColor();
    color = QColorDialog::getColor(color);
    if(color.isValid())
        curAxis->setGridLineColor(color);
}

void MainWindow::on_pBtn_Fontcolor_3_clicked()
{
    bool ok = false;
    QPen pen = curAxis->gridLinePen();
    pen = DialogPen::getPen(pen, ok);
    if(ok)
        curAxis->setGridLinePen(pen);
}

void MainWindow::on_spinBox_Tickcount_valueChanged(int arg1)
{
    curAxis->setTickCount(arg1);
}

void MainWindow::on_spinBox_minorTickcount_valueChanged(int arg1)
{
    curAxis->setMinorTickCount(arg1);
}

void MainWindow::on_chk_TickLineIsVisible_clicked(bool checked)
{
    curAxis->setLineVisible(checked);
}

void MainWindow::on_pBtn_Fontcolor_5_clicked()
{
    bool ok = false;
    QPen pen = curAxis->linePen();
    pen = DialogPen::getPen(pen, ok);
    if(ok)
        curAxis->setLinePen(pen);
}

void MainWindow::on_pBtn_Fontcolor_4_clicked()
{
    QColor color = curAxis->linePenColor();
    color = QColorDialog::getColor(color);
    if(color.isValid())
        curAxis->setLinePenColor(color);
}

void MainWindow::on_pBtn_Fontcolor_7_clicked()
{
    QColor color = curAxis->minorGridLineColor();
    color = QColorDialog::getColor(color);
    if(color.isValid())
        curAxis->setMinorGridLineColor(color);
}

void MainWindow::on_pBtn_Fontcolor_6_clicked()
{
    bool ok = false;
    QPen pen = curAxis->gridLinePen();
    pen = DialogPen::getPen(pen, ok);
    if(ok)
        curAxis->setGridLinePen(pen);
}

void MainWindow::on_chk_MinorTickLineIsVisible_clicked(bool checked)
{
    curAxis->setMinorGridLineVisible(checked);
}

效果演示

 到此這篇關於QT中QChart繪製折線圖的文章就介紹到這了,更多相關QChart繪製折線圖內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com