网站开发一般用什么语言,网站关键词如何收录,云商城app下载,厦门建设局招聘在现有Qt程序中实现可配置日志保存天数的代码示例#xff0c;分为界面修改、配置存储和核心逻辑三部分#xff1a;
// 1. 在配置文件#xff08;如settings.h#xff09;中添加保存天数的配置项
class Settings {
public:int logRetentionDays() const {return m_settings…在现有Qt程序中实现可配置日志保存天数的代码示例分为界面修改、配置存储和核心逻辑三部分
// 1. 在配置文件如settings.h中添加保存天数的配置项
class Settings {
public:int logRetentionDays() const {return m_settings.value(Log/RetentionDays, 30).toInt(); // 默认30天}void setLogRetentionDays(int days) {m_settings.setValue(Log/RetentionDays, days);}private:QSettings m_settings;
};// 2. 在界面类头文件中添加控件声明MainWindow.h
class MainWindow : public QMainWindow {Q_OBJECT
public:// ... 原有声明
private slots:void onRetentionDaysChanged(int index);void checkLogCleanup();private:QComboBox *m_retentionCombo;QTimer *m_cleanupTimer;Settings m_settings;
};// 3. 界面初始化MainWindow.cpp
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent)
{// 初始化下拉框m_retentionCombo new QComboBox(this);m_retentionCombo-addItem(3天, 3);m_retentionCombo-addItem(7天, 7);m_retentionCombo-addItem(10天, 10);// 读取保存的值int savedDays m_settings.logRetentionDays();int index m_retentionCombo-findData(savedDays);m_retentionCombo-setCurrentIndex(index ! -1 ? index : 0);connect(m_retentionCombo, QOverloadint::of(QComboBox::currentIndexChanged),this, MainWindow::onRetentionDaysChanged);// 初始化定时器每天检查m_cleanupTimer new QTimer(this);connect(m_cleanupTimer, QTimer::timeout, this, MainWindow::checkLogCleanup);m_cleanupTimer-start(24 * 60 * 60 * 1000); // 24小时
}// 4. 处理配置变更
void MainWindow::onRetentionDaysChanged(int index)
{int days m_retentionCombo-itemData(index).toInt();m_settings.setLogRetentionDays(days);checkLogCleanup(); // 可选立即执行一次清理
}// 5. 实现日志清理核心逻辑
void MainWindow::checkLogCleanup()
{QDir logDir(logs);QDate currentDate QDate::currentDate();int retentionDays m_settings.logRetentionDays();foreach (const QFileInfo fileInfo, logDir.entryInfoList(QDir::Files)) {// 从文件名解析日期假设文件名格式为log_yyyy-MM-dd.txtQString fileName fileInfo.fileName();QDate fileDate QDate::fromString(fileName.mid(4, 10), yyyy-MM-dd);if (fileDate.isValid()) {int days fileDate.daysTo(currentDate);if (days retentionDays) {QFile::remove(fileInfo.absoluteFilePath());}}}
}实现要点说明
界面控件
使用QComboBox提供3/7/10天选项使用QData关联存储实际天数值通过QSettings持久化配置
定时检查
使用QTimer每日触发清理检查首次启动时立即执行一次清理
安全增强
文件名日期解析需要验证有效性删除前可添加确认对话框生产环境慎用建议添加日志记录清理操作
扩展性
可添加最小保留天数限制如1支持自定义天数需添加QSpinBox多线程处理大量文件删除
如果需要更完整的实现可以添加以下优化
// 增强版文件日期检测同时检查文件元数据
QDate getFileDate(const QFileInfo fileInfo) {// 优先从文件名解析QDate date parseDateFromFileName(fileInfo.fileName());// 文件名无效时使用修改日期if (!date.isValid()) {date fileInfo.lastModified().date();}return date;
}// 带进度提示的清理
void MainWindow::checkLogCleanup() {QDir logDir(logs);int total logDir.count();int processed 0;foreach (const QFileInfo fileInfo, logDir.entryInfoList(QDir::Files)) {// ... 清理逻辑// 更新进度emit cleanupProgress(processed * 100 / total);QApplication::processEvents();}
}