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("成绩表格已成功保存。"));
    });
相关推荐
国服第二切图仔3 分钟前
Rust中泛型函数实现不同类型数据的比较
开发语言·后端·rust
技术砖家--Felix1 小时前
Spring Boot入门篇:快速搭建你的第一个Spring Boot应用
java·开发语言·音视频
国服第二切图仔1 小时前
Rust开发之使用Trait对象实现多态
开发语言·算法·rust
Yolo566Q1 小时前
Python驱动的无人机生态三维建模与碳储/生物量/LULC估算全流程实战技术
开发语言·python·无人机
我不是程序猿儿1 小时前
【C#】XtraMessageBox(DevExpress)与MessageBox(WinForms 标准库)的区别
开发语言·c#
玖笙&2 小时前
✨WPF编程进阶【6.1】:图形原则(附源码)
c++·c#·wpf·visual studio
s砚山s2 小时前
代码随想录刷题——二叉树篇(一)
c++·算法·leetcode
含目的基因的质粒2 小时前
Python异常、模块、包
服务器·开发语言·python
AC是你的谎言3 小时前
HTTP和HTTPS
linux·网络·c++·网络协议·学习·http·https
千码君20163 小时前
Go语言:解决 “package xxx is not in std”的思路
开发语言·后端·golang