<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- application.qdoc --> <title>Qt 4.8: Application Example</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style/superfish.css" /> <link rel="stylesheet" type="text/css" href="style/narrow.css" /> <!--[if IE]> <meta name="MSSmartTagsPreventParsing" content="true"> <meta http-equiv="imagetoolbar" content="no"> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie6.css"> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie7.css"> <![endif]--> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="style/style_ie8.css"> <![endif]--> <script src="scripts/superfish.js" type="text/javascript"></script> <script src="scripts/narrow.js" type="text/javascript"></script> </head> <body class="" onload="CheckEmptyAndLoadList();"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="narrowsearch"></div> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li> <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UIs & Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="supported-platforms.html">Supported Platforms</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search" id="sidebarsearch"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> <div id="resultdialog"> <a href="#" id="resultclose">Close</a> <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span> results:</p> <ul id="resultlist" class="all"> </ul> </div> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UIs & Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> <li><a href="all-examples.html">Examples</a></li> <li>Application Example</li> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content mainContent"> <div class="toc"> <h3><a name="toc">Contents</a></h3> <ul> <li class="level1"><a href="#mainwindow-class-definition">MainWindow Class Definition</a></li> <li class="level1"><a href="#mainwindow-class-implementation">MainWindow Class Implementation</a></li> <li class="level1"><a href="#the-main-function">The main() Function</a></li> <li class="level1"><a href="#the-resource-file">The Resource File</a></li> </ul> </div> <h1 class="title">Application Example</h1> <span class="subtitle"></span> <!-- $$$mainwindows/application-description --> <div class="descr"> <a name="details"></a> <p>Files:</p> <ul> <li><a href="mainwindows-application-mainwindow-cpp.html">mainwindows/application/mainwindow.cpp</a></li> <li><a href="mainwindows-application-mainwindow-h.html">mainwindows/application/mainwindow.h</a></li> <li><a href="mainwindows-application-main-cpp.html">mainwindows/application/main.cpp</a></li> <li><a href="mainwindows-application-application-pro.html">mainwindows/application/application.pro</a></li> <li><a href="mainwindows-application-application-qrc.html">mainwindows/application/application.qrc</a></li> </ul> <p>Images:</p> <ul> <li><a href="images/used-in-examples/mainwindows/application/images/copy.png">mainwindows/application/images/copy.png</a></li> <li><a href="images/used-in-examples/mainwindows/application/images/cut.png">mainwindows/application/images/cut.png</a></li> <li><a href="images/used-in-examples/mainwindows/application/images/new.png">mainwindows/application/images/new.png</a></li> <li><a href="images/used-in-examples/mainwindows/application/images/open.png">mainwindows/application/images/open.png</a></li> <li><a href="images/used-in-examples/mainwindows/application/images/paste.png">mainwindows/application/images/paste.png</a></li> <li><a href="images/used-in-examples/mainwindows/application/images/save.png">mainwindows/application/images/save.png</a></li> </ul> <p>The Application example shows how to implement a standard GUI application with menus, toolbars, and a status bar. The example itself is a simple text editor program built around <a href="qplaintextedit.html">QPlainTextEdit</a>.<p class="centerAlign"><img src="images/application.png" alt="Screenshot of the Application example" /></p><p>Nearly all of the code for the Application example is in the <tt>MainWindow</tt> class, which inherits <a href="qmainwindow.html">QMainWindow</a>. <a href="qmainwindow.html">QMainWindow</a> provides the framework for windows that have menus, toolbars, dock windows, and a status bar. The application provides <b>File</b>, <b>Edit</b>, and <b>Help</b> entries in the menu bar, with the following popup menus:</p> <p class="centerAlign"><img src="images/application-menus.png" alt="The Application example's menu system" /></p><p>The status bar at the bottom of the main window shows a description of the menu item or toolbar button under the cursor.</p> <p>To keep the example simple, recently opened files aren't shown in the <b>File</b> menu, even though this feature is desired in 90% of applications. The <a href="mainwindows-recentfiles.html">Recent Files</a> example shows how to implement this. Furthermore, this example can only load one file at a time. The <a href="mainwindows-sdi.html">SDI</a> and <a href="mainwindows-mdi.html">MDI</a> examples shows how to lift these restrictions.</p> <a name="mainwindow-class-definition"></a> <h2>MainWindow Class Definition</h2> <p>Here's the class definition:</p> <pre class="cpp"> <span class="keyword">class</span> MainWindow : <span class="keyword">public</span> <span class="type"><a href="qmainwindow.html">QMainWindow</a></span> { Q_OBJECT <span class="keyword">public</span>: MainWindow(); <span class="keyword">protected</span>: <span class="type">void</span> closeEvent(<span class="type"><a href="qcloseevent.html">QCloseEvent</a></span> <span class="operator">*</span>event); <span class="keyword">private</span> <span class="keyword">slots</span>: <span class="type">void</span> newFile(); <span class="type">void</span> open(); <span class="type">bool</span> save(); <span class="type">bool</span> saveAs(); <span class="type">void</span> about(); <span class="type">void</span> documentWasModified(); <span class="keyword">private</span>: <span class="type">void</span> createActions(); <span class="type">void</span> createMenus(); <span class="type">void</span> createToolBars(); <span class="type">void</span> createStatusBar(); <span class="type">void</span> readSettings(); <span class="type">void</span> writeSettings(); <span class="type">bool</span> maybeSave(); <span class="type">void</span> loadFile(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fileName); <span class="type">bool</span> saveFile(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fileName); <span class="type">void</span> setCurrentFile(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fileName); <span class="type"><a href="qstring.html">QString</a></span> strippedName(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fullFileName); <span class="type"><a href="qplaintextedit.html">QPlainTextEdit</a></span> <span class="operator">*</span>textEdit; <span class="type"><a href="qstring.html">QString</a></span> curFile; <span class="type"><a href="qmenu.html">QMenu</a></span> <span class="operator">*</span>fileMenu; <span class="type"><a href="qmenu.html">QMenu</a></span> <span class="operator">*</span>editMenu; <span class="type"><a href="qmenu.html">QMenu</a></span> <span class="operator">*</span>helpMenu; <span class="type"><a href="qtoolbar.html">QToolBar</a></span> <span class="operator">*</span>fileToolBar; <span class="type"><a href="qtoolbar.html">QToolBar</a></span> <span class="operator">*</span>editToolBar; <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>newAct; <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>openAct; <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>saveAct; <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>saveAsAct; <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>exitAct; <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>cutAct; <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>copyAct; <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>pasteAct; <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>aboutAct; <span class="type"><a href="qaction.html">QAction</a></span> <span class="operator">*</span>aboutQtAct; };</pre> <p>The public API is restricted to the constructor. In the <tt>protected</tt> section, we reimplement <a href="qwidget.html#closeEvent">QWidget::closeEvent</a>() to detect when the user attempts to close the window, and warn the user about unsaved changes. In the <tt>private slots</tt> section, we declare slots that correspond to menu entries, as well as a mysterious <tt>documentWasModified()</tt> slot. Finally, in the <tt>private</tt> section of the class, we have various members that will be explained in due time.</p> <a name="mainwindow-class-implementation"></a> <h2>MainWindow Class Implementation</h2> <pre class="cpp"> <span class="preprocessor">#include <QtGui></span> <span class="preprocessor">#include "mainwindow.h"</span></pre> <p>We start by including <tt><QtGui></tt>, a header file that contains the definition of all classes in the <a href="qtcore.html">QtCore</a> and <a href="qtgui.html">QtGui</a> libraries. This saves us from the trouble of having to include every class individually. We also include <tt>mainwindow.h</tt>.</p> <p>You might wonder why we don't include <tt><QtGui></tt> in <tt>mainwindow.h</tt> and be done with it. The reason is that including such a large header from another header file can rapidly degrade performances. Here, it wouldn't do any harm, but it's still generally a good idea to include only the header files that are strictly necessary from another header file.</p> <pre class="cpp"> MainWindow<span class="operator">::</span>MainWindow() { textEdit <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qplaintextedit.html">QPlainTextEdit</a></span>; setCentralWidget(textEdit); createActions(); createMenus(); createToolBars(); createStatusBar(); readSettings(); connect(textEdit<span class="operator">-</span><span class="operator">></span>document()<span class="operator">,</span> SIGNAL(contentsChanged())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(documentWasModified())); setCurrentFile(<span class="string">""</span>); setUnifiedTitleAndToolBarOnMac(<span class="keyword">true</span>); }</pre> <p>In the constructor, we start by creating a <a href="qplaintextedit.html">QPlainTextEdit</a> widget as a child of the main window (the <tt>this</tt> object). Then we call <a href="qmainwindow.html#setCentralWidget">QMainWindow::setCentralWidget</a>() to tell that this is going to be the widget that occupies the central area of the main window, between the toolbars and the status bar.</p> <p>Then we call <tt>createActions()</tt>, <tt>createMenus()</tt>, <tt>createToolBars()</tt>, and <tt>createStatusBar()</tt>, four private functions that set up the user interface. After that, we call <tt>readSettings()</tt> to restore the user's preferences.</p> <p>We establish a signal-slot connection between the <a href="qplaintextedit.html">QPlainTextEdit</a>'s document object and our <tt>documentWasModified()</tt> slot. Whenever the user modifies the text in the <a href="qplaintextedit.html">QPlainTextEdit</a>, we want to update the title bar to show that the file was modified.</p> <p>At the end, we set the window title using the private <tt>setCurrentFile()</tt> function. We'll come back to this later.</p> <a name="close-event-handler"></a><pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>closeEvent(<span class="type"><a href="qcloseevent.html">QCloseEvent</a></span> <span class="operator">*</span>event) { <span class="keyword">if</span> (maybeSave()) { writeSettings(); event<span class="operator">-</span><span class="operator">></span>accept(); } <span class="keyword">else</span> { event<span class="operator">-</span><span class="operator">></span>ignore(); } }</pre> <p>When the user attempts to close the window, we call the private function <tt>maybeSave()</tt> to give the user the possibility to save pending changes. The function returns true if the user wants the application to close; otherwise, it returns false. In the first case, we save the user's preferences to disk and accept the close event; in the second case, we ignore the close event, meaning that the application will stay up and running as if nothing happened.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>newFile() { <span class="keyword">if</span> (maybeSave()) { textEdit<span class="operator">-</span><span class="operator">></span>clear(); setCurrentFile(<span class="string">""</span>); } }</pre> <p>The <tt>newFile()</tt> slot is invoked when the user selects <b>File|New</b> from the menu. We call <tt>maybeSave()</tt> to save any pending changes and if the user accepts to go on, we clear the <a href="qplaintextedit.html">QPlainTextEdit</a> and call the private function <tt>setCurrentFile()</tt> to update the window title and clear the <a href="qwidget.html#windowModified-prop">windowModified</a> flag.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>open() { <span class="keyword">if</span> (maybeSave()) { <span class="type"><a href="qstring.html">QString</a></span> fileName <span class="operator">=</span> <span class="type"><a href="qfiledialog.html">QFileDialog</a></span><span class="operator">::</span>getOpenFileName(<span class="keyword">this</span>); <span class="keyword">if</span> (<span class="operator">!</span>fileName<span class="operator">.</span>isEmpty()) loadFile(fileName); } }</pre> <p>The <tt>open()</tt> slot is invoked when the user clicks <b>File|Open</b>. We pop up a <a href="qfiledialog.html">QFileDialog</a> asking the user to choose a file. If the user chooses a file (i.e., <tt>fileName</tt> is not an empty string), we call the private function <tt>loadFile()</tt> to actually load the file.</p> <pre class="cpp"> <span class="type">bool</span> MainWindow<span class="operator">::</span>save() { <span class="keyword">if</span> (curFile<span class="operator">.</span>isEmpty()) { <span class="keyword">return</span> saveAs(); } <span class="keyword">else</span> { <span class="keyword">return</span> saveFile(curFile); } }</pre> <p>The <tt>save()</tt> slot is invoked when the user clicks <b>File|Save</b>. If the user hasn't provided a name for the file yet, we call <tt>saveAs()</tt>; otherwise, we call the private function <tt>saveFile()</tt> to actually save the file.</p> <pre class="cpp"> <span class="type">bool</span> MainWindow<span class="operator">::</span>saveAs() { <span class="type"><a href="qstring.html">QString</a></span> fileName <span class="operator">=</span> <span class="type"><a href="qfiledialog.html">QFileDialog</a></span><span class="operator">::</span>getSaveFileName(<span class="keyword">this</span>); <span class="keyword">if</span> (fileName<span class="operator">.</span>isEmpty()) <span class="keyword">return</span> <span class="keyword">false</span>; <span class="keyword">return</span> saveFile(fileName); }</pre> <p>In <tt>saveAs()</tt>, we start by popping up a <a href="qfiledialog.html">QFileDialog</a> asking the user to provide a name. If the user clicks <b>Cancel</b>, the returned file name is empty, and we do nothing.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>about() { <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>about(<span class="keyword">this</span><span class="operator">,</span> tr(<span class="string">"About Application"</span>)<span class="operator">,</span> tr(<span class="string">"The <b>Application</b> example demonstrates how to "</span> <span class="string">"write modern GUI applications using Qt, with a menu bar, "</span> <span class="string">"toolbars, and a status bar."</span>)); }</pre> <p>The application's About box is done using one statement, using the <a href="qmessagebox.html#about">QMessageBox::about</a>() static function and relying on its support for an HTML subset.</p> <p>The <a href="qobject.html#tr">tr()</a> call around the literal string marks the string for translation. It is a good habit to call <a href="qobject.html#tr">tr()</a> on all user-visible strings, in case you later decide to translate your application to other languages. The <a href="internationalization.html">Internationalization with Qt</a> overview convers <a href="qobject.html#tr">tr()</a> in more detail.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>documentWasModified() { setWindowModified(textEdit<span class="operator">-</span><span class="operator">></span>document()<span class="operator">-</span><span class="operator">></span>isModified()); }</pre> <p>The <tt>documentWasModified()</tt> slot is invoked each time the text in the <a href="qplaintextedit.html">QPlainTextEdit</a> changes because of user edits. We call <a href="qwidget.html#windowModified-prop">QWidget::setWindowModified</a>() to make the title bar show that the file was modified. How this is done varies on each platform.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>createActions() { newAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="type"><a href="qicon.html">QIcon</a></span>(<span class="string">":/images/new.png"</span>)<span class="operator">,</span> tr(<span class="string">"&New"</span>)<span class="operator">,</span> <span class="keyword">this</span>); newAct<span class="operator">-</span><span class="operator">></span>setShortcuts(<span class="type"><a href="qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>New); newAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Create a new file"</span>)); connect(newAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(newFile())); openAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(<span class="type"><a href="qicon.html">QIcon</a></span>(<span class="string">":/images/open.png"</span>)<span class="operator">,</span> tr(<span class="string">"&Open..."</span>)<span class="operator">,</span> <span class="keyword">this</span>); openAct<span class="operator">-</span><span class="operator">></span>setShortcuts(<span class="type"><a href="qkeysequence.html">QKeySequence</a></span><span class="operator">::</span>Open); openAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Open an existing file"</span>)); connect(openAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(open())); ... aboutQtAct <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qaction.html">QAction</a></span>(tr(<span class="string">"About &Qt"</span>)<span class="operator">,</span> <span class="keyword">this</span>); aboutQtAct<span class="operator">-</span><span class="operator">></span>setStatusTip(tr(<span class="string">"Show the Qt library's About box"</span>)); connect(aboutQtAct<span class="operator">,</span> SIGNAL(triggered())<span class="operator">,</span> qApp<span class="operator">,</span> SLOT(aboutQt()));</pre> <p>The <tt>createActions()</tt> private function, which is called from the <tt>MainWindow</tt> constructor, creates <a href="qaction.html">QAction</a>s. The code is very repetitive, so we show only the actions corresponding to <b>File|New</b>, <b>File|Open</b>, and <b>Help|About Qt</b>.</p> <p>A <a href="qaction.html">QAction</a> is an object that represents one user action, such as saving a file or invoking a dialog. An action can be put in a <a href="qmenu.html">QMenu</a> or a <a href="qtoolbar.html">QToolBar</a>, or both, or in any other widget that reimplements <a href="qwidget.html#actionEvent">QWidget::actionEvent</a>().</p> <p>An action has a text that is shown in the menu, an icon, a shortcut key, a tooltip, a status tip (shown in the status bar), a "What's This?" text, and more. It emits a <a href="qaction.html#triggered">triggered()</a> signal whenever the user invokes the action (e.g., by clicking the associated menu item or toolbar button). We connect this signal to a slot that performs the actual action.</p> <p>The code above contains one more idiom that must be explained. For some of the actions, we specify an icon as a <a href="qicon.html">QIcon</a> to the <a href="qaction.html">QAction</a> constructor. The <a href="qicon.html">QIcon</a> constructor takes the file name of an image that it tries to load. Here, the file name starts with <tt>:</tt>. Such file names aren't ordinary file names, but rather path in the executable's stored resources. We'll come back to this when we review the <tt>application.qrc</tt> file that's part of the project.</p> <pre class="cpp"> cutAct<span class="operator">-</span><span class="operator">></span>setEnabled(<span class="keyword">false</span>); copyAct<span class="operator">-</span><span class="operator">></span>setEnabled(<span class="keyword">false</span>); connect(textEdit<span class="operator">,</span> SIGNAL(copyAvailable(<span class="type">bool</span>))<span class="operator">,</span> cutAct<span class="operator">,</span> SLOT(setEnabled(<span class="type">bool</span>))); connect(textEdit<span class="operator">,</span> SIGNAL(copyAvailable(<span class="type">bool</span>))<span class="operator">,</span> copyAct<span class="operator">,</span> SLOT(setEnabled(<span class="type">bool</span>))); }</pre> <p>The <b>Edit|Cut</b> and <b>Edit|Copy</b> actions must be available only when the <a href="qplaintextedit.html">QPlainTextEdit</a> contains selected text. We disable them by default and connect the <a href="qplaintextedit.html#copyAvailable">QPlainTextEdit::copyAvailable</a>() signal to the <a href="qaction.html#enabled-prop">QAction::setEnabled</a>() slot, ensuring that the actions are disabled when the text editor has no selection.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>createMenus() { fileMenu <span class="operator">=</span> menuBar()<span class="operator">-</span><span class="operator">></span>addMenu(tr(<span class="string">"&File"</span>)); fileMenu<span class="operator">-</span><span class="operator">></span>addAction(newAct); fileMenu<span class="operator">-</span><span class="operator">></span>addAction(openAct); fileMenu<span class="operator">-</span><span class="operator">></span>addAction(saveAct); fileMenu<span class="operator">-</span><span class="operator">></span>addAction(saveAsAct); fileMenu<span class="operator">-</span><span class="operator">></span>addSeparator(); fileMenu<span class="operator">-</span><span class="operator">></span>addAction(exitAct); editMenu <span class="operator">=</span> menuBar()<span class="operator">-</span><span class="operator">></span>addMenu(tr(<span class="string">"&Edit"</span>)); editMenu<span class="operator">-</span><span class="operator">></span>addAction(cutAct); editMenu<span class="operator">-</span><span class="operator">></span>addAction(copyAct); editMenu<span class="operator">-</span><span class="operator">></span>addAction(pasteAct); menuBar()<span class="operator">-</span><span class="operator">></span>addSeparator(); helpMenu <span class="operator">=</span> menuBar()<span class="operator">-</span><span class="operator">></span>addMenu(tr(<span class="string">"&Help"</span>)); helpMenu<span class="operator">-</span><span class="operator">></span>addAction(aboutAct); helpMenu<span class="operator">-</span><span class="operator">></span>addAction(aboutQtAct); }</pre> <p>Creating actions isn't sufficient to make them available to the user; we must also add them to the menu system. This is what <tt>createMenus()</tt> does. We create a <b>File</b>, an <b>Edit</b>, and a <b>Help</b> menu. <a href="qmainwindow.html#menuBar">QMainWindow::menuBar</a>() lets us access the window's menu bar widget. We don't have to worry about creating the menu bar ourselves; the first time we call this function, the <a href="qmenubar.html">QMenuBar</a> is created.</p> <p>Just before we create the <b>Help</b> menu, we call <a href="qmenubar.html#addSeparator">QMenuBar::addSeparator</a>(). This has no effect for most widget styles (e.g., Windows and Mac OS X styles), but for Motif-based styles this makes sure that <b>Help</b> is pushed to the right side of the menu bar. Try running the application with various styles and see the results:</p> <pre class="cpp"> application -style=windows application -style=motif application -style=cde</pre> <p>Let's now review the toolbars:</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>createToolBars() { fileToolBar <span class="operator">=</span> addToolBar(tr(<span class="string">"File"</span>)); fileToolBar<span class="operator">-</span><span class="operator">></span>addAction(newAct); fileToolBar<span class="operator">-</span><span class="operator">></span>addAction(openAct); fileToolBar<span class="operator">-</span><span class="operator">></span>addAction(saveAct); editToolBar <span class="operator">=</span> addToolBar(tr(<span class="string">"Edit"</span>)); editToolBar<span class="operator">-</span><span class="operator">></span>addAction(cutAct); editToolBar<span class="operator">-</span><span class="operator">></span>addAction(copyAct); editToolBar<span class="operator">-</span><span class="operator">></span>addAction(pasteAct); }</pre> <p>Creating toolbars is very similar to creating menus. The same actions that we put in the menus can be reused in the toolbars.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>createStatusBar() { statusBar()<span class="operator">-</span><span class="operator">></span>showMessage(tr(<span class="string">"Ready"</span>)); }</pre> <p><a href="qmainwindow.html#statusBar">QMainWindow::statusBar</a>() returns a pointer to the main window's <a href="qstatusbar.html">QStatusBar</a> widget. Like with <a href="qmainwindow.html#menuBar">QMainWindow::menuBar</a>(), the widget is automatically created the first time the function is called.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>readSettings() { <span class="type"><a href="qsettings.html">QSettings</a></span> settings(<span class="string">"Trolltech"</span><span class="operator">,</span> <span class="string">"Application Example"</span>); <span class="type"><a href="qpoint.html">QPoint</a></span> pos <span class="operator">=</span> settings<span class="operator">.</span>value(<span class="string">"pos"</span><span class="operator">,</span> <span class="type"><a href="qpoint.html">QPoint</a></span>(<span class="number">200</span><span class="operator">,</span> <span class="number">200</span>))<span class="operator">.</span>toPoint(); <span class="type"><a href="qsize.html">QSize</a></span> size <span class="operator">=</span> settings<span class="operator">.</span>value(<span class="string">"size"</span><span class="operator">,</span> <span class="type"><a href="qsize.html">QSize</a></span>(<span class="number">400</span><span class="operator">,</span> <span class="number">400</span>))<span class="operator">.</span>toSize(); resize(size); move(pos); }</pre> <p>The <tt>readSettings()</tt> function is called from the constructor to load the user's preferences and other application settings. The <a href="qsettings.html">QSettings</a> class provides a high-level interface for storing settings permanently on disk. On Windows, it uses the (in)famous Windows registry; on Mac OS X, it uses the native XML-based CFPreferences API; on Unix/X11, it uses text files.</p> <p>The <a href="qsettings.html">QSettings</a> constructor takes arguments that identify your company and the name of the product. This ensures that the settings for different applications are kept separately.</p> <p>We use <a href="qsettings.html#value">QSettings::value</a>() to extract the value of the "pos" and "size" settings. The second argument to <a href="qsettings.html#value">QSettings::value</a>() is optional and specifies a default value for the setting if there exists none. This value is used the first time the application is run.</p> <p>When restoring the position and size of a window, it's important to call <a href="qwidget.html#size-prop">QWidget::resize</a>() before <a href="qwidget.html#pos-prop">QWidget::move</a>(). The reason why is given in the <a href="application-windows.html#window-geometry">Window Geometry</a> overview.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>writeSettings() { <span class="type"><a href="qsettings.html">QSettings</a></span> settings(<span class="string">"Trolltech"</span><span class="operator">,</span> <span class="string">"Application Example"</span>); settings<span class="operator">.</span>setValue(<span class="string">"pos"</span><span class="operator">,</span> pos()); settings<span class="operator">.</span>setValue(<span class="string">"size"</span><span class="operator">,</span> size()); }</pre> <p>The <tt>writeSettings()</tt> function is called from <tt>closeEvent()</tt>. Writing settings is similar to reading them, except simpler. The arguments to the <a href="qsettings.html">QSettings</a> constructor must be the same as in <tt>readSettings()</tt>.</p> <pre class="cpp"> <span class="type">bool</span> MainWindow<span class="operator">::</span>maybeSave() { <span class="keyword">if</span> (textEdit<span class="operator">-</span><span class="operator">></span>document()<span class="operator">-</span><span class="operator">></span>isModified()) { <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>StandardButton ret; ret <span class="operator">=</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>warning(<span class="keyword">this</span><span class="operator">,</span> tr(<span class="string">"Application"</span>)<span class="operator">,</span> tr(<span class="string">"The document has been modified.\n"</span> <span class="string">"Do you want to save your changes?"</span>)<span class="operator">,</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>Save <span class="operator">|</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>Discard <span class="operator">|</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>Cancel); <span class="keyword">if</span> (ret <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>Save) <span class="keyword">return</span> save(); <span class="keyword">else</span> <span class="keyword">if</span> (ret <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>Cancel) <span class="keyword">return</span> <span class="keyword">false</span>; } <span class="keyword">return</span> <span class="keyword">true</span>; }</pre> <p>The <tt>maybeSave()</tt> function is called to save pending changes. If there are pending changes, it pops up a <a href="qmessagebox.html">QMessageBox</a> giving the user to save the document. The options are <a href="qmessagebox.html#StandardButton-enum">QMessageBox::Yes</a>, <a href="qmessagebox.html#StandardButton-enum">QMessageBox::No</a>, and <a href="qmessagebox.html#StandardButton-enum">QMessageBox::Cancel</a>. The <b>Yes</b> button is made the default button (the button that is invoked when the user presses <b>Return</b>) using the <a href="qmessagebox.html#StandardButton-enum">QMessageBox::Default</a> flag; the <b>Cancel</b> button is made the escape button (the button that is invoked when the user presses <b>Esc</b>) using the <a href="qmessagebox.html#StandardButton-enum">QMessageBox::Escape</a> flag.</p> <p>The <tt>maybeSave()</tt> function returns <tt>true</tt> in all cases, except when the user clicks <b>Cancel</b>. The caller must check the return value and stop whatever it was doing if the return value is <tt>false</tt>.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>loadFile(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fileName) { <span class="type"><a href="qfile.html">QFile</a></span> file(fileName); <span class="keyword">if</span> (<span class="operator">!</span>file<span class="operator">.</span>open(<span class="type"><a href="qfile.html">QFile</a></span><span class="operator">::</span>ReadOnly <span class="operator">|</span> <span class="type"><a href="qfile.html">QFile</a></span><span class="operator">::</span>Text)) { <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>warning(<span class="keyword">this</span><span class="operator">,</span> tr(<span class="string">"Application"</span>)<span class="operator">,</span> tr(<span class="string">"Cannot read file %1:\n%2."</span>) <span class="operator">.</span>arg(fileName) <span class="operator">.</span>arg(file<span class="operator">.</span>errorString())); <span class="keyword">return</span>; } <span class="type"><a href="qtextstream.html">QTextStream</a></span> in(<span class="operator">&</span>file); <span class="preprocessor">#ifndef QT_NO_CURSOR</span> <span class="type"><a href="qapplication.html">QApplication</a></span><span class="operator">::</span>setOverrideCursor(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>WaitCursor); <span class="preprocessor">#endif</span> textEdit<span class="operator">-</span><span class="operator">></span>setPlainText(in<span class="operator">.</span>readAll()); <span class="preprocessor">#ifndef QT_NO_CURSOR</span> <span class="type"><a href="qapplication.html">QApplication</a></span><span class="operator">::</span>restoreOverrideCursor(); <span class="preprocessor">#endif</span> setCurrentFile(fileName); statusBar()<span class="operator">-</span><span class="operator">></span>showMessage(tr(<span class="string">"File loaded"</span>)<span class="operator">,</span> <span class="number">2000</span>); }</pre> <p>In <tt>loadFile()</tt>, we use <a href="qfile.html">QFile</a> and <a href="qtextstream.html">QTextStream</a> to read in the data. The <a href="qfile.html">QFile</a> object provides access to the bytes stored in a file.</p> <p>We start by opening the file in read-only mode. The <a href="qiodevice.html#OpenModeFlag-enum">QFile::Text</a> flag indicates that the file is a text file, not a binary file. On Unix and Mac OS X, this makes no difference, but on Windows, it ensures that the "\r\n" end-of-line sequence is converted to "\n" when reading.</p> <p>If we successfully opened the file, we use a <a href="qtextstream.html">QTextStream</a> object to read in the data. <a href="qtextstream.html">QTextStream</a> automatically converts the 8-bit data into a Unicode <a href="qstring.html">QString</a> and supports various encodings. If no encoding is specified, <a href="qtextstream.html">QTextStream</a> assumes the file is written using the system's default 8-bit encoding (for example, Latin-1; see <a href="qtextcodec.html#codecForLocale">QTextCodec::codecForLocale</a>() for details).</p> <p>Since the call to <a href="qtextstream.html#readAll">QTextStream::readAll</a>() might take some time, we set the cursor to be <a href="qt.html#CursorShape-enum">Qt::WaitCursor</a> for the entire application while it goes on.</p> <p>At the end, we call the private <tt>setCurrentFile()</tt> function, which we'll cover in a moment, and we display the string "File loaded" in the status bar for 2 seconds (2000 milliseconds).</p> <pre class="cpp"> <span class="type">bool</span> MainWindow<span class="operator">::</span>saveFile(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fileName) { <span class="type"><a href="qfile.html">QFile</a></span> file(fileName); <span class="keyword">if</span> (<span class="operator">!</span>file<span class="operator">.</span>open(<span class="type"><a href="qfile.html">QFile</a></span><span class="operator">::</span>WriteOnly <span class="operator">|</span> <span class="type"><a href="qfile.html">QFile</a></span><span class="operator">::</span>Text)) { <span class="type"><a href="qmessagebox.html">QMessageBox</a></span><span class="operator">::</span>warning(<span class="keyword">this</span><span class="operator">,</span> tr(<span class="string">"Application"</span>)<span class="operator">,</span> tr(<span class="string">"Cannot write file %1:\n%2."</span>) <span class="operator">.</span>arg(fileName) <span class="operator">.</span>arg(file<span class="operator">.</span>errorString())); <span class="keyword">return</span> <span class="keyword">false</span>; } <span class="type"><a href="qtextstream.html">QTextStream</a></span> out(<span class="operator">&</span>file); <span class="preprocessor">#ifndef QT_NO_CURSOR</span> <span class="type"><a href="qapplication.html">QApplication</a></span><span class="operator">::</span>setOverrideCursor(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>WaitCursor); <span class="preprocessor">#endif</span> out <span class="operator"><</span><span class="operator"><</span> textEdit<span class="operator">-</span><span class="operator">></span>toPlainText(); <span class="preprocessor">#ifndef QT_NO_CURSOR</span> <span class="type"><a href="qapplication.html">QApplication</a></span><span class="operator">::</span>restoreOverrideCursor(); <span class="preprocessor">#endif</span> setCurrentFile(fileName); statusBar()<span class="operator">-</span><span class="operator">></span>showMessage(tr(<span class="string">"File saved"</span>)<span class="operator">,</span> <span class="number">2000</span>); <span class="keyword">return</span> <span class="keyword">true</span>; }</pre> <p>Saving a file is very similar to loading one. Here, the <a href="qiodevice.html#OpenModeFlag-enum">QFile::Text</a> flag ensures that on Windows, "\n" is converted into "\r\n" to conform to the Windows convension.</p> <pre class="cpp"> <span class="type">void</span> MainWindow<span class="operator">::</span>setCurrentFile(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fileName) { curFile <span class="operator">=</span> fileName; textEdit<span class="operator">-</span><span class="operator">></span>document()<span class="operator">-</span><span class="operator">></span>setModified(<span class="keyword">false</span>); setWindowModified(<span class="keyword">false</span>); <span class="type"><a href="qstring.html">QString</a></span> shownName <span class="operator">=</span> curFile; <span class="keyword">if</span> (curFile<span class="operator">.</span>isEmpty()) shownName <span class="operator">=</span> <span class="string">"untitled.txt"</span>; setWindowFilePath(shownName); }</pre> <p>The <tt>setCurrentFile()</tt> function is called to reset the state of a few variables when a file is loaded or saved, or when the user starts editing a new file (in which case <tt>fileName</tt> is empty). We update the <tt>curFile</tt> variable, clear the <a href="qtextdocument.html#modified-prop">QTextDocument::modified</a> flag and the associated <tt>QWidget:windowModified</tt> flag, and update the window title to contain the new file name (or <tt>untitled.txt</tt>).</p> <p>The <tt>strippedName()</tt> function call around <tt>curFile</tt> in the <a href="qwidget.html#windowTitle-prop">QWidget::setWindowTitle</a>() call shortens the file name to exclude the path. Here's the function:</p> <pre class="cpp"> <span class="type"><a href="qstring.html">QString</a></span> MainWindow<span class="operator">::</span>strippedName(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&</span>fullFileName) { <span class="keyword">return</span> <span class="type"><a href="qfileinfo.html">QFileInfo</a></span>(fullFileName)<span class="operator">.</span>fileName(); }</pre> <a name="the-main-function"></a> <h2>The main() Function</h2> <p>The <tt>main()</tt> function for this application is typical of applications that contain one main window:</p> <pre class="cpp"> <span class="preprocessor">#include <QApplication></span> <span class="preprocessor">#include "mainwindow.h"</span> <span class="type">int</span> main(<span class="type">int</span> argc<span class="operator">,</span> <span class="type">char</span> <span class="operator">*</span>argv<span class="operator">[</span><span class="operator">]</span>) { Q_INIT_RESOURCE(application); <span class="type"><a href="qapplication.html">QApplication</a></span> app(argc<span class="operator">,</span> argv); app<span class="operator">.</span>setOrganizationName(<span class="string">"Trolltech"</span>); app<span class="operator">.</span>setApplicationName(<span class="string">"Application Example"</span>); MainWindow mainWin; <span class="preprocessor">#if defined(Q_OS_SYMBIAN)</span> mainWin<span class="operator">.</span>showMaximized(); <span class="preprocessor">#else</span> mainWin<span class="operator">.</span>show(); <span class="preprocessor">#endif</span> <span class="keyword">return</span> app<span class="operator">.</span>exec(); }</pre> <a name="the-resource-file"></a> <h2>The Resource File</h2> <p>As you will probably recall, for some of the actions, we specified icons with file names starting with <tt>:</tt> and mentioned that such file names aren't ordinary file names, but path in the executable's stored resources. These resources are compiled</p> <p>The resources associated with an application are specified in a <tt>.qrc</tt> file, an XML-based file format that lists files on the disk. Here's the <tt>application.qrc</tt> file that's used by the Application example:</p> <pre class="cpp"> <!DOCTYPE RCC><RCC version="1.0"> <qresource> <file>images/copy.png</file> <file>images/cut.png</file> <file>images/new.png</file> <file>images/open.png</file> <file>images/paste.png</file> <file>images/save.png</file> </qresource> </RCC></pre> <p>The <tt>.png</tt> files listed in the <tt>application.qrc</tt> file are files that are part of the Application example's source tree. Paths are relative to the directory where the <tt>application.qrc</tt> file is located (the <tt>mainwindows/application</tt> directory).</p> <p>The resource file must be mentioned in the <tt>application.pro</tt> file so that <tt>qmake</tt> knows about it:</p> <pre class="cpp"> RESOURCES = application.qrc</pre> <p><tt>qmake</tt> will produce make rules to generate a file called <tt>qrc_application.cpp</tt> that is linked into the application. This file contains all the data for the images and other resources as static C++ arrays of compressed binary data. See <a href="resources.html">The Qt Resource System</a> for more information about resources.</p> </div> <!-- @@@mainwindows/application --> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its subsidiaries. Documentation contributions included herein are the copyrights of their respective owners.</p> <br /> <p> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> <p> Documentation sources may be obtained from <a href="http://www.qt-project.org"> www.qt-project.org</a>.</p> <br /> <p> Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p> </div> <script src="scripts/functions.js" type="text/javascript"></script> </body> </html>