Home > Articles

This chapter is from the book

This chapter is from the book

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.

03fig08.gif

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.

03fig09.gif

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 name—or 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 parent–child 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.

03fig10.gif

Figure 3.10. "Do you want to overwrite it?"

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.

03fig11.gif

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.

03fig12.gif

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020