天天看點

添加最近打開檔案功能--開發思路

一、前言

很多軟體,啟動軟體時都會自動打開最近打開的檔案,也會添加最近打開檔案清單,供使用者快速啟動工程,這是個挺實用的功能,在此記錄一下自己的思路,僅供參考,不喜勿噴,謝謝!

二、效果展示

添加最近打開檔案功能--開發思路
添加最近打開檔案功能--開發思路

三、思路分析

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());
}