对上一篇的工作C++学习笔记 | 基于Qt框架开发实时成绩显示排序系统1-CSDN博客继续优化,增加一个显示运动员每组成绩的折线图。
1)在Qt Creator的项目文件(.pro
文件)中添加对Qt Charts模块的支持:
QT += charts
2)在 AthleteModel.h 中添加
public:// 获取所有运动员的列表std::vector<Athlete> getAthletes() const;
3)在athletemodel.cpp的最后添加
std::vector<Athlete> AthleteModel::getAthletes() const {std::vector<Athlete> athletesList;for (int row = 0; row < rowCount(); ++row) {Athlete athlete;athlete.name = item(row, 0)->text().toStdString();for (int col = 1; col <= 6; ++col) { // 假设前6列是成绩athlete.scores[col - 1] = item(row, col)->text().toFloat();}athlete.totalScore = item(row, 7)->text().toFloat(); // 假设第7列是总分athletesList.push_back(athlete);}return athletesList;
}
3)需要确保UI中有一个Tool Button按钮,命名为actionBtn
4)在mainwindow.cpp中添加按钮以及其槽函数
//其他内容....
#include <QtCharts>
using namespace QtCharts;//其他代码....QAction* actBtn = new QAction(QIcon(":/ZXT.png"), "折线图");ui->actionBtn->setDefaultAction(actBtn);connect(ui->actionBtn, &QToolButton::triggered, this, [=]() {QChart *chart = new QChart();chart->setTitle("运动员成绩折线图");chart->legend()->setVisible(true);chart->legend()->setAlignment(Qt::AlignBottom);// 获取所有运动员的列表auto athletes = model->getAthletes();for (const auto &athlete : athletes) {QLineSeries *series = new QLineSeries();series->setName(QString::fromStdString(athlete.name));for (int i = 0; i < 6; ++i) { // 假设有6次成绩series->append(i + 1, athlete.scores[i]); // 添加每次成绩到序列}chart->addSeries(series);}chart->createDefaultAxes();if (!athletes.empty()) {// 假设所有运动员至少有一次成绩,设置水平轴范围为1到6chart->axes(Qt::Horizontal).first()->setRange(1, 6);// 这里需要确定垂直轴的合适范围float maxScore = 0;float minScore = 200;for (const auto &athlete : athletes) {for (float score : athlete.scores) {if (score > maxScore) maxScore = score;if (score < minScore) minScore = score;}}chart->axes(Qt::Vertical).first()->setRange(minScore, maxScore);}QChartView *chartView = new QChartView(chart);chartView->setRenderHint(QPainter::Antialiasing);// 创建一个新窗口显示这个图表QMainWindow *chartWindow = new QMainWindow();chartWindow->setCentralWidget(chartView);chartWindow->resize(1000, 500);chartWindow->setWindowIcon(QIcon(":/ZXT.png"));chartWindow->setWindowTitle("成绩折线图");chartWindow->show();});ui->actionBtn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);//其他代码....
5)最后导出安装
参考这篇博文:
QT导出安装文件的方法(WIN和Andriod平台)_qt怎么导出项目-CSDN博客