天天看点

添加最近打开文件功能--开发思路

一、前言

很多软件,启动软件时都会自动打开最近打开的文件,也会添加最近打开文件列表,供用户快速启动工程,这是个挺实用的功能,在此记录一下自己的思路,仅供参考,不喜勿喷,谢谢!

二、效果展示

添加最近打开文件功能--开发思路
添加最近打开文件功能--开发思路

三、思路分析

class MainWindow : public QMainWindow {
    Q_OBJECT
public:
    MainWindow(QWidget* parent = 0)
    {
        ...
        
        getRecentFiles();   //读取最近打开的文件
        
        ...
    }
    void openProject();
    void openProject(QString filePath);
    
public slots:
    void loadRecentFile(QAction* action);
    
private:
    QString recentFilePath;            //最近打开工程文本文件路径
    QStringList m_recentFiles;      //最近打开的文件(路径容器)

    ...
};

void MainWindow::getRecentFiles()    //读取最近打开文件
{
    recentFilePath = QCoreApplication::applicationDirPath() + "/recentFilePath.txt";    //最近打开工程文本文件路径
    QFile recentFile(recentFilePath);
    if(recentFile.exists()) {    //如果文本文件存在
        if(recentFile.open(QIODevice::ReadOnly | QIODevice::Text)) {    //只读方式打开
            m_recentFiles.clear();    //清空路径容器
            while(!recentFile.atEnd()) {
                QString lineStr = recentFile.readLine();    //读取一行
                lineStr = lineStr.mid(0,lineStr.lastIndexOf("pow")+3);    //去除换行'\n'
                m_recentFiles << lineStr;    //路径加入容器
            }
        }
    }else {    //如果文本文件不存在
        recentFile.open(QIODevice::WriteOnly | QIODevice::Text);    //创建文本文件
        recentFile.close();
        return;
    }
    if(m_recentFiles.size() > 0) {    //如果路径容器不为空
        m_recentFiles = m_recentFiles.toSet().toList();    //去掉路径容器中重复项
    }

    if (m_recentFiles.count() > 0) {    //将路径容器项转化为菜单项,添加到菜单栏
        recentMenu = new QMenu;    //创建菜单
        QAction* Menu_action;    //创建菜单项
        for(int i=0; i<m_recentFiles.size(); ++i) {    //遍历路径容器
            if(!QFile::exists(m_recentFiles.at(i))) {    //如果路径文件不存在,跳过
                continue;
            }
            Menu_action = new QAction(m_recentFiles.at(i));    //依据路径容器创建一个Action
            recentMenu->addAction(Menu_action);    //将创建的Action添加到菜单
        }
        connect(recentMenu, SIGNAL(triggered(QAction*)),this,SLOT(loadRecentFile(QAction*)));    //绑定菜单项点击动作
        ui->recentFileAct->setMenu(recentMenu);    //将创建的菜单设置到菜单栏中的Action中
    }
    //openProject(m_recentFiles.at(m_recentFiles.size()-1));  //打开最近一次打开的工程
}

void MainWindow::openProject()
{
    ...

    //添加最近打开文件
    QFile recentFile(recentFilePath);
    if(!recentFile.exists()) {  //如果文件不存在则创建
        recentFile.open(QIODevice::WriteOnly | QIODevice::Text);
        recentFile.close();
    }else {
        if(recentFile.open(QIODevice::Append | QIODevice::Text)) {
            QFileInfo fInfo(fileName);
            QTextStream stream(&recentFile);
            stream << fInfo.absoluteFilePath() << endl;
            recentFile.close();
            getRecentFiles();
        }
    }

    ...
}

void MainWindow::openProject(QString filePath)
{
    ...
}

void MainWindow::loadRecentFile(QAction* action)
{
    openProject(action->text());
}