C++ Qt框架开发 | 基于Qt框架开发实时成绩显示排序系统(3) 保存表格数据

对上两篇篇的工作C++ Qt框架开发| 基于Qt框架开发实时成绩显示排序系统(1)-CSDN博客C++ Qt框架开发 | 基于Qt框架开发实时成绩显示排序系统(2)折线图显示-CSDN博客继续优化,增加一个保存按钮,用于保存成绩数据。

1)在ui界面添加一个按钮

将其命名为saveBtn。

2)在mainwindow.cpp中添加如下槽函数
cpp 复制代码
    QAction* sBtn = new QAction("保存");
    ui->saveBtn->setDefaultAction(sBtn);
    connect(ui->saveBtn, &QToolButton::triggered, this, [=]() {
        // 弹出保存文件对话框
        QString filePath = QFileDialog::getSaveFileName(this, tr("保存成绩"), "", tr("CSV文件 (*.csv)"));
        if (filePath.isEmpty()) return; // 用户取消操作

        QFile file(filePath);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QMessageBox::warning(this, tr("保存失败"), tr("无法打开文件进行写入"));
            return;
        }

        QTextStream out(&file);

        // 写入标题行
        QStringList headers;
        for (int column = 0; column < proxyModel->columnCount(); ++column) {
            headers << proxyModel->headerData(column, Qt::Horizontal).toString();
        }
        out << headers.join(",") + "\n";

        // 写入数据行
        for (int row = 0; row < proxyModel->rowCount(); ++row) {
            QStringList rowItems;
            for (int column = 0; column < proxyModel->columnCount(); ++column) {
                QModelIndex index = proxyModel->index(row, column);
                rowItems << proxyModel->data(index).toString();
            }
            out << rowItems.join(",") + "\n";
        }

        file.close(); // 关闭文件
        QMessageBox::information(this, tr("保存成功"), tr("成绩表格已成功保存。"));
    });
相关推荐
信奥卷王12 小时前
2025年9月GESPC++三级真题解析(含视频)
开发语言·c++·算法
喵了几个咪13 小时前
Golang微服务框架kratos实现Socket.IO服务
开发语言·微服务·golang
q***420513 小时前
PHP使用Redis实战实录2:Redis扩展方法和PHP连接Redis的多种方案
开发语言·redis·php
qq_4335545414 小时前
C++ 稀疏表
开发语言·c++·算法
Bona Sun14 小时前
单片机手搓掌上游戏机(十二)—esp8266运行gameboy模拟器之编译上传
c语言·c++·单片机·游戏机
帅中的小灰灰14 小时前
C++编程观察者设计模式
数据库·c++·设计模式
z***y86214 小时前
Java数据挖掘开发
java·开发语言·数据挖掘
软件开发技术深度爱好者14 小时前
Python库/包/模块管理工具
开发语言·python
bubiyoushang88814 小时前
基于MATLAB的自然图像梯度分布重尾特性验证方案
开发语言·matlab
MSTcheng.15 小时前
【C++STL】priority_queue 模拟实现与仿函数实战
开发语言·c++