Qt柱状图,需要使用到QChart模块,因此需要在安装Qt时勾选上QChart模块。然后在工程.pro文件中加上 QT += charts
参考代码:
//MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <QPushButton>
#include <QLineEdit>QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic: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 <QtCharts/QChartView>
#include <QtCharts/QBarSeries>
#include <QtCharts/QBarSet>
#include <QtCharts/QLegend>
#include <QtCharts/QBarCategoryAxis>QT_CHARTS_USE_NAMESPACEMainWindow::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(); // 实例化QChartchart->addSeries(series); //往Chart里添加serieschart->setTitle(QString::fromLocal8Bit("排序后数据")); //设置表格头chart->setAnimationOptions(QChart::SeriesAnimations);QStringList categories; //创建字符串Listcategories << "data";QBarCategoryAxis *axis = new QBarCategoryAxis(); //实例化坐标轴文字标识轴axis->append(categories); //将字符串列表append到文字标识轴里chart->createDefaultAxes();//创建默认的坐标轴(笛卡尔坐标),一定要有这一句chart->setAxisX(axis, series);//设置坐标轴chart->legend()->setVisible(true); //设置图例为显示状态chart->legend()->setAlignment(Qt::AlignBottom);//设置图例的显示位置在底部//显示容器 QChartViewQChartView *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;
}
效果图: