Home > Articles > Programming > C/C++

This chapter is from the book

Multiple Document Interface

Applications that provide multiple documents within the main window's central area are called multiple document interface applications, or MDI applications. In Qt, an MDI application is created by using the QMdiArea class as the central widget and by making each document window a QMdiArea subwindow.

It is conventional for MDI applications to provide a Window menu that includes some commands for managing both the windows and the list of windows. The active window is identified with a checkmark. The user can make any window active by clicking its entry in the Window menu.

In this section, we will develop the MDI Editor application shown in Figure 6.16 to demonstrate how to create an MDI application and how to implement its Window menu. All the application's menus are shown in Figure 6.17.

editor.jpg

Figure 6.16 The MDI Editor application

editor-menus.jpg

Figure 6.17 The MDI Editor application's menus

The application consists of two classes: MainWindow and Editor. The code is supplied with the book's examples, and since most of it is the same or similar to the Spreadsheet application from Part I, we will present only the MDI-relevant code.

Let's start with the MainWindow class.

MainWindow::MainWindow()
{
    mdiArea = new QMdiArea;
    setCentralWidget(mdiArea);
    connect(mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)),
            this, SLOT(updateActions()));

    createActions();
    createMenus();
    createToolBars();
    createStatusBar();

    setWindowIcon(QPixmap(":/images/icon.png"));
    setWindowTitle(tr("MDI Editor"));
    QTimer::singleShot(0, this, SLOT(loadFiles()));
}

In the MainWindow constructor, we create a QMdiArea widget and make it the central widget. We connect the QMdiArea's subWindowActivated() signal to the slot we will use to keep the window menu up-to-date, and where we ensure that actions are enabled or disabled depending on the application's state.

At the end of the constructor, we set a single-shot timer with a 0-millisecond interval to call the loadFiles() function. Such timers time out as soon as the event loop is idle. In practice, this means that the constructor will finish, and then after the main window has been shown, loadFiles() will be called. If we did not do this and there were a lot of large files to load, the constructor would not finish until all the files were loaded, and meanwhile, the user would not see anything on-screen and might think that the application had failed to start.

void MainWindow::loadFiles()
{
    QStringList args = QApplication::arguments();
    args.removeFirst();
    if (!args.isEmpty()) {
        foreach (QString arg, args)
            openFile(arg);
        mdiArea->cascadeSubWindows();
    } else {
        newFile();
    }
    mdiArea->activateNextSubWindow();
}

If the user started the application with one or more file names on the command line, this function attempts to load each file and at the end cascades the subwindows so that the user can easily see them. Qt-specific command-line options, such as -style and -font, are automatically removed from the argument list by the QApplication constructor. So, if we write

mdieditor -style motif readme.txt

on the command line, QApplication::arguments() returns a QStringList containing two items ("mdieditor" and "readme.txt"), and the MDI Editor application starts up with the document readme.txt.

If no file is specified on the command line, a single new empty editor subwindow is created so that the user can start typing straight away. The call to activateNextSubWindow() means that an editor window is given the focus, and ensures that the updateActions() function is called to update the Window menu and enable and disable actions according to the application's state.

void MainWindow::newFile()
{
    Editor *editor = new Editor;
    editor->newFile();
    addEditor(editor);
}

The newFile() slot corresponds to the File|New menu option. It creates an Editor widget and passes it on to the addEditor() private function.

void MainWindow::open()
{
    Editor *editor = Editor::open(this);
    if (editor)
    addEditor(editor);
}

The open() function corresponds to File|Open. It calls the static Editor::open() function, which pops up a file dialog. If the user chooses a file, a new Editor is created, the file's text is read in, and if the read is successful, a pointer to the Editor is returned. If the user cancels the file dialog, or if the reading fails, a null pointer is returned and the user is notified of the error. It makes more sense to implement the file operations in the Editor class than in the MainWindow class, because each Editor needs to maintain its own independent state.

void MainWindow::addEditor(Editor *editor)
{
    connect(editor, SIGNAL(copyAvailable(bool)),
            cutAction, SLOT(setEnabled(bool)));
    connect(editor, SIGNAL(copyAvailable(bool)),
            copyAction, SLOT(setEnabled(bool)));

    QMdiSubWindow *subWindow = mdiArea->addSubWindow(editor);
    windowMenu->addAction(editor->windowMenuAction());
    windowActionGroup->addAction(editor->windowMenuAction());
    subWindow->show();
}

The addEditor() private function is called from newFile() and open() to complete the initialization of a new Editor widget. It starts by establishing two signal–slot connections. These connections ensure that Edit|Cut and Edit|Copy are enabled or disabled depending on whether there is any selected text.

Because we are using MDI, it is possible that multiple Editor widgets will be in use. This is a concern since we are only interested in responding to the copyAvailable(bool) signal from the active Editor window, not from the others. But these signals can only ever be emitted by the active window, so this isn't a problem in practice.

The QMdiArea::addSubWindow() function creates a new QMdiSubWindow, puts the widget it is passed as a parameter inside the subwindow, and returns the subwindow. Next, we create a QAction representing the window to the Window menu. The action is provided by the Editor class, which we will cover in a moment. We also add the action to a QActionGroup object. The QActionGroup ensures that only one Window menu item is checked at a time. Finally, we call show() on the new QMdiSubWindow to make it visible.

void MainWindow::save()
{
    if (activeEditor())
        activeEditor()->save();
}

The save() slot calls Editor::save() on the active editor, if there is one. Again, the code that performs the real work is located in the Editor class.

Editor *MainWindow::activeEditor()
{
    QMdiSubWindow *subWindow = mdiArea->activeSubWindow();
    if (subWindow)
        return qobject_cast<Editor *>(subWindow->widget());
    return 0;
}

The activeEditor() private function returns the widget held inside the active subwindow as an Editor pointer, or a null pointer if there isn't an active subwindow.

void MainWindow::cut()
{
    if (activeEditor())
        activeEditor()->cut();
}

The cut() slot calls Editor::cut() on the active editor. We don't show the copy() and paste() slots because they follow the same pattern.

void MainWindow::updateActions()
{
    bool hasEditor = (activeEditor() != 0);
    bool hasSelection = activeEditor()
                        && activeEditor()->textCursor().hasSelection();

    saveAction->setEnabled(hasEditor);
    saveAsAction->setEnabled(hasEditor);
    cutAction->setEnabled(hasSelection);
    copyAction->setEnabled(hasSelection);
    pasteAction->setEnabled(hasEditor);
    closeAction->setEnabled(hasEditor);
    closeAllAction->setEnabled(hasEditor);
    tileAction->setEnabled(hasEditor);
    cascadeAction->setEnabled(hasEditor);
    nextAction->setEnabled(hasEditor);
    previousAction->setEnabled(hasEditor);
    separatorAction->setVisible(hasEditor);

    if (activeEditor())
        activeEditor()->windowMenuAction()->setChecked(true);
}

The subWindowActivated() signal is emitted every time a new subwindow becomes activated, and when the last subwindow is closed (in which case, its parameter is a null pointer). This signal is connected to the updateActions() slot.

Most menu options make sense only if there is an active window, so we disable them if there isn't one. At the end, we call setChecked() on the QAction representing the active window. Thanks to the QActionGroup, we don't need to explicitly uncheck the previously active window.

void MainWindow::createMenus()
{
    ...
    windowMenu = menuBar()->addMenu(tr("&Window"));
    windowMenu->addAction(closeAction);
    windowMenu->addAction(closeAllAction);
    windowMenu->addSeparator();
    windowMenu->addAction(tileAction);
    windowMenu->addAction(cascadeAction);
    windowMenu->addSeparator();
    windowMenu->addAction(nextAction);
    windowMenu->addAction(previousAction);
    windowMenu->addAction(separatorAction);
    ...
}

The createMenus() private function populates the Window menu with actions. All the actions are typical of such menus and are easily implemented using QMdiArea's closeActiveSubWindow(), closeAllSubWindows(), tileSubWindows(), and cascadeSubWindows() slots. Every time the user opens a new window, it is added to the Window menu's list of actions. (This is done in the addEditor() function that we saw on page 160.) When the user closes an editor window, its action in the Window menu is deleted (since the action is owned by the editor window), and so the action is automatically removed from the Window menu.

void MainWindow::closeEvent(QCloseEvent *event)
{
    mdiArea->closeAllSubWindows();
    if (!mdiArea->subWindowList().isEmpty()) {
        event->ignore();
    } else {
        event->accept();
    }
}

The closeEvent() function is reimplemented to close all subwindows, causing each subwindow to receive a close event. If one of the subwindows "ignores" its close event (because the user canceled an "unsaved changes" message box), we ignore the close event for the MainWindow; otherwise, we accept it, resulting in Qt closing the entire application. If we didn't reimplement closeEvent() in MainWindow, the user would not be given the opportunity to save unsaved changes.

We have now finished our review of MainWindow, so we can move on to the Editor implementation. The Editor class represents one subwindow. It is derived from QTextEdit, which provides the text editing functionality. In a real-world application, if a code editing component is required, we might also consider using Scintilla, available for Qt as QScintilla from http://www.riverbankcomputing.co.uk/qscintilla/.

Just as any Qt widget can be used as a stand-alone window, any Qt widget can be put inside a QMdiSubWindow and used as a subwindow in an MDI area.

Here's the class definition:

class Editor : public QTextEdit
{
    Q_OBJECT

public:
    Editor(QWidget *parent = 0);

    void newFile();
    bool save();
    bool saveAs();
    QSize sizeHint() const;
    QAction *windowMenuAction() const { return action; }

    static Editor *open(QWidget *parent = 0);
    static Editor *openFile(const QString &fileName,
                            QWidget *parent = 0);

protected:
    void closeEvent(QCloseEvent *event);

private slots:
    void documentWasModified();

private:
    bool okToContinue();
    bool saveFile(const QString &fileName);
    void setCurrentFile(const QString &fileName);
    bool readFile(const QString &fileName);
    bool writeFile(const QString &fileName);
    QString strippedName(const QString &fullFileName);

    QString curFile;
    bool isUntitled;
    QAction *action;
};

Four of the private functions that were in the Spreadsheet application's MainWindow class (p. 59) are also present in the Editor class: okToContinue(), saveFile(), setCurrentFile(), and strippedName().

Editor::Editor(QWidget *parent)
    : QTextEdit(parent)
{
    action = new QAction(this);
    action->setCheckable(true);
    connect(action, SIGNAL(triggered()), this, SLOT(show()));
    connect(action, SIGNAL(triggered()), this, SLOT(setFocus()));

    isUntitled = true;

    connect(document(), SIGNAL(contentsChanged()),
            this, SLOT(documentWasModified()));

    setWindowIcon(QPixmap(":/images/document.png"));
    setWindowTitle("[*]");
    setAttribute(Qt::WA_DeleteOnClose);
}

First, we create a QAction representing the editor in the application's Window menu and connect that action to the show() and setFocus() slots.

Since we allow users to create any number of editor windows, we must make some provision for naming them so that they can be distinguished before they have been saved for the first time. One common way of handling this is to allocate names that include a number (e.g., document1.txt). We use the isUntitled variable to distinguish between names supplied by the user and names we have created programmatically.

We connect the text document's contentsChanged() signal to the private documentWasModified() slot. This slot simply calls setWindowModified(true).

Finally, we set the Qt::WA_DeleteOnClose attribute to prevent memory leaks when the user closes an Editor window.

void Editor::newFile()
{
    static int documentNumber = 1;

    curFile = tr("document%1.txt").arg(documentNumber);
    setWindowTitle(curFile + "[*]");
    action->setText(curFile);
    isUntitled = true;
    ++documentNumber;
}

The newFile() function generates a name like document1.txt for the new document. The code belongs in newFile(), rather than the constructor, because we don't want to consume numbers when we call open() to open an existing document in a newly created Editor. Since documentNumber is declared static, it is shared across all Editor instances.

The "[*]" marker in the window title is a place marker for where we want the asterisk to appear when the file has unsaved changes on platforms other than Mac OS X. On Mac OS X, unsaved documents have a dot in their window's close button. We covered this place marker in Chapter 3 (p. 61).

In addition to creating new files, users often want to open existing files, picked from either a file dialog or a list such as a recently opened files list. Two static functions are provided to support these uses: open() for choosing a file name from the file system, and openFile() to create an Editor and to read into it the contents of a specified file.

Editor *Editor::open(QWidget *parent)
{
    QString fileName =
            QFileDialog::getOpenFileName(parent, tr("Open"), ".");
    if (fileName.isEmpty())
        return 0;

    return openFile(fileName, parent);
}

The static open() function pops up a file dialog through which the user can choose a file. If a file is chosen, openFile() is called to create an Editor and to read in the file's contents.

Editor *Editor::openFile(const QString &fileName, QWidget *parent)
{
    Editor *editor = new Editor(parent);

    if (editor->readFile(fileName)) {
        editor->setCurrentFile(fileName);
        return editor;
    } else {
        delete editor;
        return 0;
    }
}

This static function begins by creating a new Editor widget, and then attempts to read in the specified file. If the read is successful, the Editor is returned; otherwise, the user is informed of the problem (in readFile()), the editor is deleted, and a null pointer is returned.

bool Editor::save()
{
    if (isUntitled) {
        return saveAs();
    } else {
        return saveFile(curFile);
    }
}

The save() function uses the isUntitled variable to determine whether it should call saveFile() or saveAs().

void Editor::closeEvent(QCloseEvent *event)
{
    if (okToContinue()) {
        event->accept();
    } else {
        event->ignore();
    }
}

The closeEvent() function is reimplemented to allow the user to save unsaved changes. The logic is coded in the okToContinue() function, which pops up a message box that asks, "Do you want to save your changes?" If okToContinue() returns true, we accept the close event; otherwise, we "ignore" it and leave the window unaffected by it.

void Editor::setCurrentFile(const QString &fileName)
{
    curFile = fileName;
    isUntitled = false;
    action->setText(strippedName(curFile));
    document()->setModified(false);
    setWindowTitle(strippedName(curFile) + "[*]");
    setWindowModified(false);
}

The setCurrentFile() function is called from openFile() and saveFile() to update the curFile and isUntitled variables, to set the window title and action text, and to set the document's "modified" flag to false. Whenever the user modifies the text in the editor, the underlying QTextDocument emits the contentsChanged() signal and sets its internal "modified" flag to true.

QSize Editor::sizeHint() const
{
    return QSize(72 * fontMetrics().width('x'),
                 25 * fontMetrics().lineSpacing());
}

Finally, the sizeHint() function returns a size based on the width of the letter 'x' and the height of a text line. QMdiArea uses the size hint to give an initial size to the window.

MDI is one way of handling multiple documents simultaneously. On Mac OS X, the preferred approach is to use multiple top-level windows. We covered this approach in the "Multiple Documents" section of Chapter 3.

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