|
- /*******************************
- * Copyright (C) 2025-.
- *
- * File Name: communicationhistory.cpp
- * Description: 通信历史记录模块头文件,提供通信数据的保存和读取功能
- * Others:
- * Version: 1.0.0
- * Author: lipengpeng
- * Date: 2025-7-25
- *******************************/
-
- #include "communicationhistory.h"
-
- /**
- * @brief 保存文本内容到指定文件
- * @param parent 父窗口指针,用于对话框的模态显示
- * @param edit 包含待保存数据的文本编辑框指针
- * @return bool 保存成功返回true,用户取消或失败返回false
- * @note 功能流程:
- * 1. 弹出标准文件保存对话框
- * 2. 以追加模式打开文件(保留历史记录)
- * 3. 自动处理文件内容分隔(添加换行符)
- * 4. 使用UTF-8编码保存文本
- * 5. 错误处理包含用户提示
- */
- bool saveDate(QWidget *parent, QTextEdit *edit)
- {
- // 弹出文件保存对话框,默认保存到用户主目录的note.txt文件
- QString fileName = QFileDialog::getSaveFileName(
- parent,
- "保存文本", // 对话框标题
- QDir::homePath() + "/note.txt", // 默认路径和文件名
- "文本文件 (*.txt);;所有文件 (*)"); // 文件过滤器
-
- // 检查用户是否取消操作
- if (fileName.isEmpty())
- {
- return false;
- }
-
- // 以追加模式和文本模式打开文件
- QFile file(fileName);
- if (!file.open(QIODevice::Append | QIODevice::Text))
- {
- QMessageBox::warning(parent,
- "错误",
- QString("无法打开文件\n%1").arg(file.errorString()));
- return false;
- }
-
- // 如果文件已有内容,先追加换行符保持内容分隔
- if (file.size() > 0)
- {
- if (file.write("\n") == -1)
- {
- // 检查换行符写入是否成功
- QMessageBox::warning(parent, "错误", "无法写入分隔符");
- file.close();
- return false;
- }
- }
-
- // 设置UTF-8编码并写入文本内容
- QTextStream out(&file);
- out.setCodec("UTF-8");
- out << edit->toPlainText();
-
- // 检查流状态确保写入成功
- if (out.status() != QTextStream::Ok)
- {
- QMessageBox::warning(parent, "错误", "写入文件时发生错误");
- file.close();
- return false;
- }
-
- file.close();
- return true;
- }
-
- /**
- * @brief 从文件读取文本内容
- * @param parent 父窗口指针,用于对话框的模态显示
- * @param edit 用于显示读取内容的文本编辑框指针
- * @return bool 读取成功返回true,用户取消或失败返回false
- * @note 功能流程:
- * 1. 弹出标准文件打开对话框
- * 2. 以只读模式打开文件
- * 3. 使用UTF-8编码读取内容
- * 4. 错误处理包含用户提示
- */
- bool readDate(QWidget *parent, QTextEdit *edit)
- {
- // 弹出文件打开对话框,默认从用户主目录开始浏览
- QString fileName = QFileDialog::getOpenFileName(
- parent,
- "打开文本", // 对话框标题
- QDir::homePath(), // 默认路径
- "文本文件 (*.txt);;所有文件 (*)"); // 文件过滤器
-
- // 检查用户是否取消操作
- if (fileName.isEmpty())
- {
- return false;
- }
-
- // 以只读模式和文本模式打开文件
- QFile file(fileName);
- if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
- {
- QMessageBox::warning(parent,
- "错误",
- QString("无法读取文件\n%1").arg(file.errorString()));
- return false;
- }
-
- // 设置UTF-8编码并读取全部内容
- QTextStream in(&file);
- in.setCodec("UTF-8");
- QString content = in.readAll();
-
- // 检查流状态确保读取成功
- if (in.status() != QTextStream::Ok)
- {
- QMessageBox::warning(parent, "错误", "读取文件时发生错误");
- file.close();
- return false;
- }
-
- // 将内容设置到文本编辑框
- edit->setPlainText(content);
- file.close();
- return true;
- }
|