Implementing the File Menu
In this section, we will implement the slots and private functions necessary to make the File menu options work.
void MainWindow::newFile() { if (maybeSave()) { spreadsheet->clear(); setCurrentFile(""); } }
The newFile() slot is called when the user clicks the File|New menu option or clicks the New toolbar button. The maybeSave() private function asks the user "Do you want to save your changes?" if there are unsaved changes. It returns true if the user chooses either Yes or No (saving the document on Yes), and it returns false if the user chooses Cancel. The setCurrentFile() private function updates the window's caption to indicate that an untitled document is being edited.
bool MainWindow::maybeSave() { if (modified) { int ret = QMessageBox::warning(this, tr("Spreadsheet"), tr("The document has been modified.\n" "Do you want to save your changes?"), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel | QMessageBox::Escape); if (ret == QMessageBox::Yes) return save(); else if (ret == QMessageBox::Cancel) return false; } return true; }
In maybeSave(), we display the message box shown in Figure 3.8. The message box has a Yes, a No, and a Cancel button. The QMessageBox::Default modifier makes Yes the default button. The QMessageBox::Escape modifier makes the Esc key a synonym for No.
Figure 3.8. "Do you want to save your changes?"
The call to warning() may look a bit complicated at first sight, but the general syntax is straightforward:
QMessageBox::warning(parent, caption, messageText, button0, button1, ...);
QMessageBox also provides information(), question(), and critical(), which behave like warning() but display a different icon.
Figure 3.9. Message box icons
void MainWindow::open() { if (maybeSave()) { QString fileName = QFileDialog::getOpenFileName(".", fileFilters, this); if (!fileName.isEmpty()) loadFile(fileName); } }
The open() slot corresponds to File|Open. Like newFile(), it first calls maybeSave() to handle any unsaved changes. Then it uses the static convenience function QFileDialog::getOpenFileName() to obtain a file name. The function pops up a file dialog, lets the user choose a file, and returns the file nameor an empty string if the user clicked Cancel.
We give the getOpenFileName() function three arguments. The first argument tells it which directory it should start from, in our case the current directory. The second argument, fileFilters, specifies the file filters. A file filter consists of a descriptive text and a wildcard pattern. In the MainWindow constructor, fileFilters was initialized as follows:
fileFilters = tr("Spreadsheet files (*.sp)");
Had we supported comma-separated values files and Lotus 1-2-3 files in addition to Spreadsheet's native file format, we would have initialized the variable as follows:
fileFilters = tr("Spreadsheet files (*.sp)\n" "Comma-separated values files (*.csv)\n" "Lotus 1-2-3 files (*.wk?)");
Finally, the third argument to getOpenFileName() specifies that the QFileDialog that pops up should be a child of the main window.
The parentchild relationship doesn't mean the same thing for dialogs as for other widgets. A dialog is always a top-level widget (a window in its own right), but if it has a parent, it is centered on top of the parent by default. A child dialog also shares the parent's taskbar entry.
void MainWindow::loadFile(const QString &fileName) { if (spreadsheet->readFile(fileName)) { setCurrentFile(fileName); statusBar()->message(tr("File loaded"), 2000); } else { statusBar()->message(tr("Loading canceled"), 2000); } }
The loadFile() private function was called in open() to load the file. We make it an independent function because we will need the same functionality to load recently opened files.
We use Spreadsheet::readFile() to read the file from the disk. If loading is successful, we call setCurrentFile() to update the window's caption. Otherwise, Spreadsheet::loadFile() will have already notified the user of the problem through a message box. In general, it is good practice to let the lower-level components issue error messages, since they can provide the precise details of what went wrong.
In both cases, we display a message in the status bar for 2000 milliseconds (2 seconds) to keep the user informed about what the application is doing.
bool MainWindow::save() { if (curFile.isEmpty()) { return saveAs(); } else { saveFile(curFile); return true; } } void MainWindow::saveFile(const QString &fileName) { if (spreadsheet->writeFile(fileName)) { setCurrentFile(fileName); statusBar()->message(tr("File saved"), 2000); } else { statusBar()->message(tr("Saving canceled"), 2000); } }
The save() slot corresponds to File|Save. If the file already has a name because it was opened before or has already been saved, save() calls saveFile() with that name; otherwise, it simply calls saveAs().
bool MainWindow::saveAs() { QString fileName = QFileDialog::getSaveFileName(".", fileFilters, this); if (fileName.isEmpty()) return false; if (QFile::exists(fileName)) { int ret = QMessageBox::warning(this, tr("Spreadsheet"), tr("File %1 already exists. \n" "Do you want to overwrite it?") .arg(QDir::convertSeparators(fileName)), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No | QMessageBox::Escape); if (ret == QMessageBox::No) return true; } if (!fileName.isEmpty()) saveFile(fileName); return true; }
The saveAs() slot corresponds to File|Save As. We call QFileDialog::getSaveFileName() to obtain a file name from the user. If the user clicks Cancel, we return false, which is propagated up to maybeSave(). Otherwise, the returned file name may be a new name or the name of an existing file. In the case of an existing file, we call QMessageBox::warning() to display the message box shown in Figure 3.10.
The text we passed to the message box is
tr("File %1 already exists\n" "Do you want to override it?") .arg(QDir::convertSeparators(fileName))
The QString::arg() function replaces the lowest-numbered "%n" parameter with its argument and returns the resulting string. For example, if the file name is A:\tab04.sp, the code above is equivalent to
"File A:\\tab04.sp already exists.\n" "Do you want to override it?"
assuming that the application isn't translated into another language. The QDir::convertSeparators() call converts forward slashes, which Qt uses as a portable directory separator, into the platform-specific separator ('/' on Unix and Mac OS X, '\' on Windows).
void MainWindow::closeEvent(QCloseEvent *event) { if (maybeSave()) { writeSettings(); event->accept(); } else { event->ignore(); } }
When the user clicks File|Exit, or clicks X in the window's title bar, the QWidget::close() slot is called. This sends a "close" event to the widget. By reimplementing QWidget::closeEvent(), we can intercept attempts to close the main window and decide whether we want the window to close or not.
If there are unsaved changes and the user chooses Cancel, we "ignore" the event and leave the window unaffected by it. Otherwise, we accept the event, resulting in Qt closing the window and the application terminating.
void MainWindow::setCurrentFile(const QString &fileName) { curFile = fileName; modLabel->clear(); modified = false; if (curFile.isEmpty()) { setCaption(tr("Spreadsheet")); } else { setCaption(tr("%1 - %2").arg(strippedName(curFile)) .arg(tr("Spreadsheet"))); recentFiles.remove(curFile); recentFiles.push_front(curFile); updateRecentFileItems(); } } QString MainWindow::strippedName(const QString &fullFileName) { return QFileInfo(fullFileName).fileName(); }
In setCurrentFile(), we set the curFile private variable that stores the name of the file being edited, clear the MOD status indicator, and update the caption. Notice how arg() is used with two %n parameters. The first call to arg() replaces "%1" the second call replaces "%2". It would have been easier to write
setCaption(strippedName(curFile) + tr(" - Spreadsheet"));
but using arg() gives more flexibility to translators. We remove the file's path with strippedName() to make the file name more user-friendly.
If there is a file name, we update recentFiles, the application's recently opened files list. We call remove() to remove any occurrence of the file name in the list; then we call push_front() to add the file name as the first item. Calling remove() first is necessary to avoid duplicates. After updating the list, we call the private function updateRecentFileItems() to update the entries in the File menu.
The recentFiles variable is of type QStringList (list of QStrings). Chapter 11 explains container classes such as QStringList in detail and how they relate to the C++ Standard Template Library (STL).
This almost completes the implementation of the File menu. There is one function and one supporting slot that we have not implemented yet. Both are concerned with managing the recently opened files list.
Figure 3.11. File menu with recently opened files
void MainWindow::updateRecentFileItems() { while ((int)recentFiles.size() > MaxRecentFiles) recentFiles.pop_back(); for (int i = 0; i < (int)recentFiles.size(); ++i) { QString text = tr("&%1 %2") .arg(i + 1) .arg(strippedName(recentFiles[i])); if (recentFileIds[i] == 1) { if (i == 0) fileMenu->insertSeparator(fileMenu->count() 2); recentFileIds[i] = fileMenu->insertItem(text, this, SLOT(openRecentFile(int)), 0, 1, fileMenu->count() 2); fileMenu->setItemParameter(recentFileIds[i], i); } else { fileMenu->changeItem(recentFileIds[i], text); } } }
The updateRecentFileItems() private function is called to update the recently opened files menu items. We begin by making sure that there are no more items in the recentFiles list than are allowed (MaxRecentFiles, defined as 5 in mainwindow.h), removing any extra items from the end of the list.
Then, for each entry, we either create a new menu item or reuse an existing item if one exists. The very first time we create a menu item, we also insert a separator. We do this here and not in createMenus() to ensure that we never display two separators in a row. The setItemParameter() call will be explained in a moment.
It may seem strange that we create items in updateRecentFileItems() but never delete items. This is because we can assume that the recently opened files list never shrinks during a session.
The QPopupMenu::insertItem() function we called has the following syntax:
fileMenu->insertItem(text, receiver, slot, accelerator, id, index);
The text is the text displayed in the menu. We use strippedName() to remove the path from the file names. We could keep the full file names, but that would make the File menu very wide. If full file names are preferred, the best solution is to put the recently opened files in a submenu.
The receiver and slot parameters specify the slot that should be called when the user chooses the item. In our example, we connect to MainWindow's openRecentFile(int) slot.
For accelerator and id, we pass default values, meaning that the menu item has no accelerator and an automatically generated ID. We store the generated ID in the recentFileIds array so that we can access the items later.
The index is the position where we want to insert the item. By passing the value fileMenu->count() - 2, we insert it above the Exit item's separator.
void MainWindow::openRecentFile(int param) { if (maybeSave()) loadFile(recentFiles[param]); }
The openRecentFile() slot is where everything falls into place. The slot is called when a recently opened file is chosen from the File menu. The int parameter is the value that we set earlier with setItemParameter(). We chose the values in such a way that we can use them magically as indexes into the recentFiles list.
Figure 3.12. Managing recently opened files
This is one way to solve the problem. A less elegant solution would have been to create five actions and connect them to five separate slots.