1.
定义recent files 最大数量,即多少个recent files action;
如:#define MaxRecentFiles 15
定义存放recent files action的QAction;
如: QAction recentFileActs[ MaxRecentFiles ];
2.
初始化recent files action;
pseudo code:
for (int i = 0; i < MaxRecentFiles; ++i)
{
recentFileActs[i] = new QAction(this);
recentFileActs[i]->setVisible(false);
connect(recentFileActs[i], SIGNAL(triggered()),
this, SLOT(openRecentFile()));
}
3.create menu
fileMenu = menuBar()->addMenu(tr("&File"));
QMenu *recentFiles = new QMenu(tr("Recent Files"));
for (int i = 0; i < MaxRecentFiles; ++i)
recentFiles ->addAction(recentFileActs[i]);
fileMenu->addMenu(recentFiles);
4.updateRecentFileActions()
void MainWindow::updateRecentFileActions()
{
QSettings settings;
QStringList files = settings.value("recentFileList").toStringList();
int numRecentFiles = qMin(files.size(), (int)MaxRecentFiles);
for (int i = 0; i < numRecentFiles; ++i) {
//QString text = tr("&%1 %2").arg(i + 1).arg(QFileInfo(fullFileName).fileName());
QString text = files[i]; //文件的全路径名称
recentFileActs[i]->setText(text); // important
recentFileActs[i]->setData(files[i]); // important
recentFileActs[i]->setVisible(true); // important
}
for (int j = numRecentFiles; j < MaxRecentFiles; ++j)
recentFileActs[j]->setVisible(false);
separatorAct->setVisible(numRecentFiles > 0);
}
5. openRecentFile() slots:
void MainWindow::openRecentFile()
{
QAction *action = qobject_cast<QAction *>(sender());
if (action)
loadFile(action->data().toString() );
}
6.
void MainWindow::loadFile(const QString &fileName)
{
QFile file(fileName);
if (!file.open(QFile::ReadOnly | QFile::Text)) {
QMessageBox::warning(this, tr("Recent Files"),
tr("Cannot read file %1:/n%2.")
.arg(fileName)
.arg(file.errorString()));
return;
}
QTextStream in(&file);
QApplication::setOverrideCursor(Qt::WaitCursor);
textEdit->setPlainText(in.readAll());
QApplication::restoreOverrideCursor();
setCurrentFile(fileName);
statusBar()->showMessage(tr("File loaded"), 2000);
}
7.
void MainWindow::setCurrentFile(const QString &fileName)
{
curFile = fileName;
setWindowFilePath(curFile);
QSettings settings;
QStringList files = settings.value("recentFileList").toStringList();
files.removeAll(fileName);
files.prepend(fileName);
while (files.size() > MaxRecentFiles)
files.removeLast();
settings.setValue("recentFileList", files);
foreach (QWidget *widget, QApplication::topLevelWidgets()) {
MainWindow *mainWin = qobject_cast<MainWindow *>(widget);
if (mainWin)
mainWin->updateRecentFileActions();
}
}