Qt 输入一组数,排序后用柱状图显示

Qt柱状图,需要使用到QChart模块,因此需要在安装Qt时勾选上QChart模块。然后在工程.pro文件中加上 QT += charts

参考代码:

//MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include 
#include 
#include 

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

public slots:
    void slotBtnClicked();

private:
    Ui::MainWindow *ui;
    QLineEdit *edit;
    QPushButton *btn;
};


#endif // MAINWINDOW_H

//MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"


#include 
#include 
#include 
#include 
#include 

QT_CHARTS_USE_NAMESPACE



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

    edit = new QLineEdit(this);
    edit->move(50,50);
    edit->resize(300,30);

    btn = new QPushButton(this);
    btn->setText(QString::fromLocal8Bit("排序"));
    btn->move(400,50);
    btn->resize(100,30);
    connect(btn, SIGNAL(clicked()), this, SLOT(slotBtnClicked()));

    this->resize(600,100);

}

void MainWindow::slotBtnClicked()
{
    QString str = edit->text();
    QStringList list = str.split(" ");
    list.erase(std::remove_if(list.begin(), list.end(), [](const QString& tmp){return tmp.isEmpty();}), list.end());

    for(int i=0; i<list.count(); i++){
        for(int j=i+1; j<list.count(); j++){
            if(list[i].toInt() > list[j].toInt()){
                QString tmp = list[i];
                list[i] = list[j];
                list[j] = tmp;
            }
        }
    }


    QBarSeries *series = new QBarSeries();
    for(auto it:list){
        QBarSet *set = new QBarSet(it);
        *set << it.toInt();
        series->append(set);
    }

    QChart *chart = new QChart(); // 实例化QChart
    chart->addSeries(series);    //往Chart里添加series
    chart->setTitle(QString::fromLocal8Bit("排序后数据"));  //设置表格头
    chart->setAnimationOptions(QChart::SeriesAnimations);


    QStringList categories;  //创建字符串List
    categories << "data";
    QBarCategoryAxis *axis = new QBarCategoryAxis();   //实例化坐标轴文字标识轴
    axis->append(categories);   //将字符串列表append到文字标识轴里
    chart->createDefaultAxes();//创建默认的坐标轴(笛卡尔坐标),一定要有这一句
    chart->setAxisX(axis, series);//设置坐标轴
    chart->legend()->setVisible(true); //设置图例为显示状态
    chart->legend()->setAlignment(Qt::AlignBottom);//设置图例的显示位置在底部

    //显示容器 QChartView
    QChartView *chartView = new QChartView(chart, this);  //添加Chart到QChartView上
    chartView->setRenderHint(QPainter::Antialiasing);
    chartView->move(50,100);
    chartView->resize(600,400);
    chartView->setVisible(true);

    this->resize(900,600);
}

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


效果图:
Qt 输入一组数,排序后用柱状图显示_第1张图片

你可能感兴趣的:(qt,c++)