Sophie

Sophie

distrib > Mandriva > 8.2 > i586 > media > contrib > by-pkgid > 112b0974ad288f6cd55bf971ee6026a9 > files > 2143

libqt3-devel-3.0.2-2mdk.i586.rpm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- /tmp/qt-3.0-reggie-28534/qt-x11-free-3.0.2/doc/application-walkthrough.doc:36 -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Walkthrough: A Simple Application</title>
<style type="text/css"><!--
h3.fn,span.fn { margin-left: 1cm; text-indent: -1cm; }
a:link { color: #004faf; text-decoration: none }
a:visited { color: #672967; text-decoration: none }
body { background: #ffffff; color: black; }
--></style>
</head>
<body>

<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr bgcolor="#E5E5E5">
<td valign=center>
 <a href="index.html">
<font color="#004faf">Home</font></a>
 | <a href="classes.html">
<font color="#004faf">All&nbsp;Classes</font></a>
 | <a href="mainclasses.html">
<font color="#004faf">Main&nbsp;Classes</font></a>
 | <a href="annotated.html">
<font color="#004faf">Annotated</font></a>
 | <a href="groups.html">
<font color="#004faf">Grouped&nbsp;Classes</font></a>
 | <a href="functions.html">
<font color="#004faf">Functions</font></a>
</td>
<td align="right" valign="center"><img src="logo32.png" align="right" width="64" height="32" border="0"></td></tr></table><h1 align=center>Walkthrough: A Simple Application</h1>

 
<p> 
<p> This walkthrough shows simple use of <a href="qmainwindow.html">QMainWindow</a>, <a href="qmenubar.html">QMenuBar</a>, <a href="qpopupmenu.html">QPopupMenu</a>, <a href="qtoolbar.html">QToolBar</a> and <a href="qstatusbar.html">QStatusBar</a> - classes that every
modern application window tends to use.
<p> It further illustrates some aspects of <a href="qwhatsthis.html">QWhatsThis</a> (for simple help) and a
typical <em>main()</em> using <a href="qapplication.html">QApplication</a>.
<p> Finally, it shows a typical printout function based on <a href="qprinter.html">QPrinter</a>.
<p> <h2>The declaration of ApplicationWindow</h2>
<p> Here's the header file in full:
<p> <pre>/****************************************************************************
** $Id:  qt/application.h   3.0.2   edited Oct 12 12:18 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#ifndef APPLICATION_H
#define APPLICATION_H

#include &lt;<a href="qmainwindow-h.html">qmainwindow.h</a>&gt;

class QTextEdit;

class ApplicationWindow: public <a href="qmainwindow.html">QMainWindow</a>
{
    <a href="metaobjects.html#Q_OBJECT">Q_OBJECT</a>

public:
    ApplicationWindow();
    ~ApplicationWindow();

protected:
    void closeEvent( <a href="qcloseevent.html">QCloseEvent</a>* );

private slots:
    void newDoc();
    void choose();
    void load( const <a href="qstring.html">QString</a> &amp;fileName );
    void save();
    void saveAs();
    void print();

    void about();
    void aboutQt();

private:
    <a href="qprinter.html">QPrinter</a> *printer;
    <a href="qtextedit.html">QTextEdit</a> *e;
    <a href="qstring.html">QString</a> filename;
};


#endif
</pre>

<p> It declares a class that inherits <a href="qmainwindow.html">QMainWindow</a>, with slots and private
variables.  The class predeclaration of <a href="qtextedit.html">QTextEdit</a> at the beginning
(instead of an include) helps to speed up compiles.  With this trick, make
depend won't insist on recompiling every <em>.cpp</em> file that includes <em>application.h</em> when <em>qtextedit.h</em> changes.
<p> <a name="simplemain"></a>
<h2>A simple main()</h2>
<p> Let's first have a look at <em>examples/main.cpp</em>, in full ...
<p> <pre>/****************************************************************************
** $Id:  qt/main.cpp   3.0.2   edited Oct 12 12:18 $
**
** Copyright (C) 1992-2000 Trolltech AS.  All rights reserved.
**
** This file is part of an example program for Qt.  This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/

#include &lt;<a href="qapplication-h.html">qapplication.h</a>&gt;
#include "application.h"

int main( int argc, char ** argv ) {
    <a href="qapplication.html">QApplication</a> a( argc, argv );
    ApplicationWindow * mw = new ApplicationWindow();
    mw-&gt;<a href="qwidget.html#setCaption">setCaption</a>( "Qt Example - Application" );
    mw-&gt;<a href="qwidget.html#show">show</a>();
<a name="x1954"></a><a name="x1952"></a>    a.<a href="qobject.html#connect">connect</a>( &amp;a, SIGNAL(<a href="qapplication.html#lastWindowClosed">lastWindowClosed</a>()), &amp;a, SLOT(<a href="qapplication.html#quit">quit</a>()) );
    return a.<a href="qapplication.html#exec">exec</a>();
}
</pre>

<p> ... and go over <em>main()</em> in detail.
<p> 

<pre>    int main( int argc, char ** argv ) {
        <a href="qapplication.html">QApplication</a> a( argc, argv );
</pre>
<p> With the above line, we create a <a href="qapplication.html">QApplication</a> object with the usual 
constructor and let it
parse <em>argc</em> and <em>argv</em>. QApplication itself takes care of X11-specific
command-line options like <em>-geometry</em>, thus the program automatically
behaves the way X clients are expected to.
<p> <pre>        ApplicationWindow * mw = new ApplicationWindow();
        mw-&gt;<a href="qwidget.html#setCaption">setCaption</a>( "Qt Example - Application" );
    <a name="x6"></a>    mw-&gt;<a href="qwidget.html#show">show</a>();
</pre>
<p> We create an <em>ApplicationWindow</em> as a top-level widget, set its window
system caption to "Document 1", and <em>show()</em> it.
<p> <a name="close"></a>
<pre>        a.<a href="qobject.html#connect">connect</a>( &amp;a, SIGNAL(<a href="qapplication.html#lastWindowClosed">lastWindowClosed</a>()), &amp;a, SLOT(<a href="qapplication.html#quit">quit</a>()) );
</pre>
<p> When the application's last window is closed, it should quit. Both,
the signal and the slot are predefined members of <a href="qapplication.html">QApplication</a>.
<p> <pre>        return a.<a href="qapplication.html#exec">exec</a>();
</pre>
<p> Having completed the application's initialization, we start the main
event loop (the GUI), and eventually return the error code
that QApplication returns when it leaves the event loop.
<p> <pre>    }
</pre>
<p> <a name="ApplicationWindow"></a>
<h2>The Implementation of ApplicationWindow</h2>
<p> 

<p> Since the implementation is quite large (almost 300 lines) we 
won't bore you with the preliminary headerfile <em>#includes</em>. Before we 
start with the constructor there are however three <em>#include</em> lines
worth mentioning:
<p> <pre>    #include "filesave.xpm"
    #include "fileopen.xpm"
    #include "fileprint.xpm"
</pre>
<p> The tool buttons in our application wouldn't be real without icons.
These icons can be found in the above xpm files. If you ever moved
a program to a different location and wondered why icons were missing
afterwards you will probably agree that it is a good idea to compile
them into the binary. This is what we are doing here.
<p> <pre>    ApplicationWindow::ApplicationWindow()
        : <a href="qmainwindow.html">QMainWindow</a>( 0, "example application main window", WDestructiveClose )
    {
</pre>
<p> <em>ApplicationWindow</em> inherits <a href="qmainwindow.html">QMainWindow</a>, the Qt class that provides
typical application main windows, with menu bars, toolbars, etc.
<p> <pre>        printer = new <a href="qprinter.html">QPrinter</a>;
</pre>
<p> The application example can print things, and we chose to have a
<a href="qprinter.html">QPrinter</a> object lying around so that when the user changes a setting
during one printing, the new setting will be the default next time.
<p> <pre>        <a href="qpixmap.html">QPixmap</a> openIcon, saveIcon, printIcon;
</pre>
<p> For simplicity reasons, our example has no more than three commands
in the toolbar.
The above variables are used to hold an icon for each of them.
<p> <pre>        <a href="qtoolbar.html">QToolBar</a> * fileTools = new <a href="qtoolbar.html">QToolBar</a>( this, "file operations" );
</pre>
<p> We create a toolbar in <em>this</em> window ...
<p> <pre>        fileTools-&gt;<a href="qtoolbar.html#setLabel">setLabel</a>( "File Operations" );
</pre>
<p> ... and define a title for it. When a user drags the toolbar out 
of its location and drops it somewhere on the desktop, the 
toolbar-window will show "File Operations" as caption.
<p> <pre>        openIcon = QPixmap( fileopen );
        QToolButton * fileOpen
            = new <a href="qtoolbutton.html">QToolButton</a>( openIcon, "Open File", <a href="qstring.html#QString-null">QString::null</a>,
                               this, SLOT(choose()), fileTools, "open file" );
</pre>
<p> Now we create the first tool button for the <em>fileTools</em> toolbar
with the appropriate icon and the tool-tip text "Open File".
The <em>fileopen.xpm</em> we included at the beginning 
contains the definition of a pixmap named <em>fileopen</em>.
This we use as the icon to illustrate our first tool button.  
<p> <pre>        saveIcon = QPixmap( filesave );
        QToolButton * fileSave
            = new <a href="qtoolbutton.html">QToolButton</a>( saveIcon, "Save File", QString::null,
                               this, SLOT(save()), fileTools, "save file" );

        printIcon = QPixmap( fileprint );
        QToolButton * filePrint
            = new <a href="qtoolbutton.html">QToolButton</a>( printIcon, "Print File", QString::null,
                               this, SLOT(print()), fileTools, "print file" );
</pre>
<p> Likewise we create two more tool buttons in this toolbar, each with 
appropriate icons and tool-tip text.  All three buttons are connected
to appropriate slots in this object; for example, the "Print File" button 
to <A HREF="#printer"><em>ApplicationWindow::print()</A></em>.
<p> <pre>        (void)QWhatsThis::whatsThisButton( fileTools );
</pre>
<p> The fourth button in the toolbar is somewhat peculiar: it's the one that
provides "What's This?" help.  This must be set up using a special
function, as its mouse interface is different from usual.
<p> <pre>        const char * fileOpenText = "&lt;p&gt;&lt;img source=\"fileopen\"&gt; "
                     "Click this button to open a &lt;em&gt;new file&lt;/em&gt;. &lt;br&gt;"
                     "You can also select the &lt;b&gt;Open&lt;/b&gt; command "
                     "from the &lt;b&gt;File&lt;/b&gt; menu.&lt;/p&gt;";

        QWhatsThis::<a href="qwhatsthis.html#add">add</a>( fileOpen, fileOpenText );
</pre>
<p> With the above line we add the "What's This?" help-text to the 
<em>fileOpen</em> button...
<p> <pre>        QMimeSourceFactory::<a href="qmimesourcefactory.html#defaultFactory">defaultFactory</a>()-&gt;setPixmap( "fileopen", openIcon );
</pre>
<p> ... and tell the rich-text engine that when a help-text (like the one
saved in <em>fileOpenText</em>) requests an image named "fileopen", the <em>openIcon</em> pixmap is used.
<p> <pre>        const char * fileSaveText = "&lt;p&gt;Click this button to save the file you "
                     "are editing. You will be prompted for a file name.\n"
                     "You can also select the &lt;b&gt;Save&lt;/b&gt; command "
                     "from the &lt;b&gt;File&lt;/b&gt; menu.&lt;/p&gt;";

        QWhatsThis::<a href="qwhatsthis.html#add">add</a>( fileSave, fileSaveText );
        const char * filePrintText = "Click this button to print the file you "
                     "are editing.\n You can also select the Print "
                     "command from the File menu.";

        QWhatsThis::<a href="qwhatsthis.html#add">add</a>( filePrint, filePrintText );
</pre>
<p> The "What's This?" help of the remaining two buttons doesn't make use
of pixmaps, therefore all we have to do is to add the help-text to the button.
Be however careful: To invoke the rich-text elements in <em>fileSaveText</em>,
the entire string must be surrounded by &lt;p&gt; and &lt;/p&gt;. In <em>filePrintText</em>,
we don't have rich-text elements, so this is not necessary.
<p> <pre>        <a href="qpopupmenu.html">QPopupMenu</a> * file = new <a href="qpopupmenu.html">QPopupMenu</a>( this );
        <a href="qmainwindow.html#menuBar">menuBar</a>()-&gt;insertItem( "&amp;File", file );
</pre>
<p> Next we create a <a href="qpopupmenu.html">QPopupMenu</a> for the <em>File</em> menu and 
add it to the menu bar. With the ampersand previous to the letter F,
we allow the user to use the shortcut <em>Alt+F</em> to open this menu.
<p> <pre>        file-&gt;<a href="qmenudata.html#insertItem">insertItem</a>( "&amp;New", this, SLOT(newDoc()), CTRL+Key_N );
</pre>
<p> Its first entry is connected to the (yet to be implementled) slot <em>newDoc()</em>. When the user chooses this <em>New</em> entry (e.g. via typing the
letter N as marked by the ampersand) or uses the
<em>Ctrl+N</em> accelerator, a new editor-window will pop up.  
<p> <pre>        int id;
        id = file-&gt;<a href="qmenudata.html#insertItem">insertItem</a>( openIcon, "&amp;Open...",
                               this, SLOT(choose()), CTRL+Key_O );
        file-&gt;<a href="qmenudata.html#setWhatsThis">setWhatsThis</a>( id, fileOpenText );

        id = file-&gt;<a href="qmenudata.html#insertItem">insertItem</a>( saveIcon, "&amp;Save",
                               this, SLOT(save()), CTRL+Key_S );
        file-&gt;<a href="qmenudata.html#setWhatsThis">setWhatsThis</a>( id, fileSaveText );

        id = file-&gt;<a href="qmenudata.html#insertItem">insertItem</a>( "Save &amp;As...", this, SLOT(saveAs()) );
        file-&gt;<a href="qmenudata.html#setWhatsThis">setWhatsThis</a>( id, fileSaveText );
</pre>
<p> We populate the <em>File</em> menu with three more commands (<em>Open</em>, <em>Save</em> and
<em>Save</em> As), and set "What's This?" help for them.  Note in particular
that "What's This?" help and pixmaps are used in both the toolbar (above)
and the menu bar (here).
<p> <pre>        file-&gt;<a href="qmenudata.html#insertSeparator">insertSeparator</a>();
</pre>
<p> Then we insert a separator, ... 
<p> <pre>        id = file-&gt;<a href="qmenudata.html#insertItem">insertItem</a>( printIcon, "&amp;Print...",
                               this, SLOT(print()), CTRL+Key_P );
        file-&gt;<a href="qmenudata.html#setWhatsThis">setWhatsThis</a>( id, filePrintText );

        file-&gt;<a href="qmenudata.html#insertSeparator">insertSeparator</a>();

        file-&gt;<a href="qmenudata.html#insertItem">insertItem</a>( "&amp;Close", this, SLOT(<a href="qwidget.html#close">close</a>()), CTRL+Key_W );
        file-&gt;<a href="qmenudata.html#insertItem">insertItem</a>( "&amp;Quit", qApp, SLOT( <a href="qapplication.html#closeAllWindows">closeAllWindows</a>() ), CTRL+Key_Q );
</pre>
<p> ... the <em>Print</em> command with "What's This?" help, another separator and
two more commands (<em>Close</em> and <em>Quit</em>) without "What's This?" and pixmaps.
In case of the <em>Close</em> command, the signal is connected 
to the <em>close()</em> slot of the respective <em>ApplicationWindow</em> object whilst
the <em>Quit</em> command affects the entire application.
<p> Because <em>ApplicationWindow</em> is a <a href="qwidget.html">QWidget</a>, the <em>close()</em> function
triggers a call to <A HREF="#closeEvent"><em>closeEvent()</A></em> which we will
implement later.
<p> <A NAME="common_constructor"></A>
<pre>        <a href="qmainwindow.html#menuBar">menuBar</a>()-&gt;insertSeparator();
</pre>
<p> Now that we are done with the File menu we shift our focus back to the
menu bar and insert a separator. From now on 
further menu bar entries will be aligned to the right if the windows system style 
suggests so.
<p> <pre>        <a href="qpopupmenu.html">QPopupMenu</a> * help = new <a href="qpopupmenu.html">QPopupMenu</a>( this );
        <a href="qmainwindow.html#menuBar">menuBar</a>()-&gt;insertItem( "&amp;Help", help );

        help-&gt;<a href="qmenudata.html#insertItem">insertItem</a>( "&amp;About", this, SLOT(about()), Key_F1 );
        help-&gt;<a href="qmenudata.html#insertItem">insertItem</a>( "About &amp;Qt", this, SLOT(aboutQt()) );
        help-&gt;<a href="qmenudata.html#insertSeparator">insertSeparator</a>();
        help-&gt;<a href="qmenudata.html#insertItem">insertItem</a>( "What's &amp;This", this, SLOT(<a href="qmainwindow.html#whatsThis">whatsThis</a>()), SHIFT+Key_F1 );
</pre>
<p> We create a <em>Help</em> menu, add it to the menu bar, and insert a few
commands. Depending on the style it will appear on the right hand 
side of the menu bar or not.
<p> <pre>        e = new <a href="qtextedit.html">QTextEdit</a>( this, "editor" );
        e-&gt;<a href="qwidget.html#setFocus">setFocus</a>();
        <a href="qmainwindow.html#setCentralWidget">setCentralWidget</a>( e );
</pre>
<p> Now we create a simple text-editor, set the initial focus to it,
and make it the central widget of this window.
<p> <a href="qmainwindow.html#centralWidget">QMainWindow::centralWidget</a>() is the heart of the entire application:
It's what menu bar, statusbar and toolbars are all arranged around.  Since
the central widget is a text editing widget, we reveal at this line that
our simple application is a text editor. :)
<p> <pre>        <a href="qmainwindow.html#statusBar">statusBar</a>()-&gt;message( "Ready", 2000 );
</pre>
<p> We make the statusbar say "Ready" for two seconds at startup, just to
tell the user that this window has finished initialization and can be
used.
<p> <pre>        <a href="qwidget.html#resize">resize</a>( 450, 600 );
</pre>
<p> Finally it's time to resize the new window to a a nice default size.
<p> <pre>    }
</pre>
<p> At this stage, we are done with the constructor. Among others we have learned 
about the classic way of creating menus and toolbars. There is
however a more modern approach to deal with this: actions that
help you saving some work. You may
have a look at how the <em>ApplicationWindow</em> constructor is implemented
using 
<A HREF="simple-application-action.html">actions</A>. Here
we'll continue with the destructor. 
<p> <pre>    ApplicationWindow::~ApplicationWindow()
    {
        delete printer;
    }
</pre>
<p> The only thing an <em>ApplicationWindow</em> widget needs to do in its destructor 
is  to delete the
printer it created.  All other objects are child widgets, which Qt
will delete as appropriate.
<p> Now our task is to implement all the slots mentioned in the header file
and used in the constructor.
<p> <A NAME="newDoc()"></A>
<pre>    void ApplicationWindow::newDoc()
    {
        ApplicationWindow *ed = new ApplicationWindow;
        ed-&gt;<a href="qwidget.html#setCaption">setCaption</a>("Qt Example - Application");
        ed-&gt;<a href="qwidget.html#show">show</a>();
    }
</pre>
<p> This slot, connected to the <em>File->New</em> menu item, simply creates a 
new <em>ApplicationWindow</em> and shows it.
<p> <A NAME="choose()"></A>
<pre>    void ApplicationWindow::choose()
    {
        <a href="qstring.html">QString</a> fn = QFileDialog::<a href="qfiledialog.html#getOpenFileName">getOpenFileName</a>( QString::null, QString::null,
                                                   this);
        if ( !fn.<a href="qstring.html#isEmpty">isEmpty</a>() )
            load( fn );
        else
            <a href="qmainwindow.html#statusBar">statusBar</a>()-&gt;message( "Loading aborted", 2000 );
    }
</pre>
<p> The <em>choose()</em> slot is connected to the <em>Open</em> menu item and
tool button.  With a little help from <a href="qfiledialog.html#getOpenFileName">QFileDialog::getOpenFileName</a>(), it
asks the user for a file name and then either loads that file or gives an
error message in the statusbar.
<p> <pre>    void ApplicationWindow::load( const <a href="qstring.html">QString</a> &amp;fileName )
    {
        <a href="qfile.html">QFile</a> f( fileName );
        if ( !f.<a href="qfile.html#open">open</a>( <a href="qfile.html#open">IO_ReadOnly</a> ) )
            return;

        <a href="qtextstream.html">QTextStream</a> ts( &amp;f );
        e-&gt;<a href="qtextedit.html#setText">setText</a>( ts.<a href="qtextstream.html#read">read</a>() );
        e-&gt;<a href="qtextedit.html#setModified">setModified</a>( FALSE );
        <a href="qwidget.html#setCaption">setCaption</a>( fileName );
        <a href="qmainwindow.html#statusBar">statusBar</a>()-&gt;message( "Loaded document " + fileName, 2000 );
    }
</pre>
<p> This function loads a file into the editor. When it's done, it sets the
window system caption to the file name and displays a success message in
the statusbar for two seconds.  With files that exist but are not
readable, nothing happens.
<p> <A NAME="save()"></A>
<pre>    void ApplicationWindow::save()
    {
        if ( filename.isEmpty() ) {
            saveAs();
            return;
        }

        <a href="qstring.html">QString</a> text = e-&gt;<a href="qtextedit.html#text">text</a>();
        <a href="qfile.html">QFile</a> f( filename );
        if ( !f.<a href="qfile.html#open">open</a>( <a href="qfile.html#open">IO_WriteOnly</a> ) ) {
            <a href="qmainwindow.html#statusBar">statusBar</a>()-&gt;message( QString("Could not write to %1").arg(filename),
                                  2000 );
            return;
        }

        <a href="qtextstream.html">QTextStream</a> t( &amp;f );
        t &lt;&lt; text;
        f.<a href="qfile.html#close">close</a>();
</pre>
<p> As its name suggests, this function saves the current file. 
If no filename has been
specified so far, the <A HREF="#saveAs()"><em>saveAs()</A></em> routine is called. 
Unwritable files cause the <em>ApplicationWindow</em> object to provide
an error-message in the statusbar. Note that there are more than
one possibilities 
to achieve this: compare the above <em>statusBar()->message()</em> line 
with the appropriate code in the <em>load()</em> function.
<p> <pre>        e-&gt;<a href="qtextedit.html#setModified">setModified</a>( FALSE );
</pre>
<p> Tell the editor that the contents haven't been edited since the last
save.  When the user does some further editing and wishes 
to close the window without explicit saving, 
<A HREF="#closeEvent"><em>ApplicationWindow::closeEvent()</A></em>  will ask about it.
<p> <pre>        <a href="qwidget.html#setCaption">setCaption</a>( filename );
</pre>
<p> It may be that the document was saved under a different name than the
old caption suggests, so we set the window caption just to be sure.
<p> <pre>        <a href="qmainwindow.html#statusBar">statusBar</a>()-&gt;message( QString( "File %1 saved" ).arg( filename ), 2000 );
    }
</pre>
<p> With a message in the statusbar, we inform the user that the file
was saved successfully.
<p> <A NAME="saveAs()"></A>
<pre>    void ApplicationWindow::saveAs()
    {
        <a href="qstring.html">QString</a> fn = QFileDialog::<a href="qfiledialog.html#getSaveFileName">getSaveFileName</a>( QString::null, QString::null,
                                                   this );
        if ( !fn.<a href="qstring.html#isEmpty">isEmpty</a>() ) {
            filename = fn;
            save();
        } else {
            <a href="qmainwindow.html#statusBar">statusBar</a>()-&gt;message( "Saving aborted", 2000 );
        }
    }
</pre>
<p> This function asks for a new name, saves the document under that name,
and implicitly changes the window system caption to the new name.
<p> <a name="printer"></a>
<p> <pre>    void ApplicationWindow::print()
    {
</pre><pre>        const int Margin = 10;
        int pageNo = 1;
</pre>
<p> <em>print()</em> is called by the <em>File->Print</em> menu item and the <em>filePrint</em> 
tool button.
<p> Because we don't want to print to the very edges of the paper, we use a
little margin: 10 points.  Furthermore we keep track of the page count.
<p> <pre>        if ( printer-&gt;<a href="qprinter.html#setup">setup</a>(this) ) {               // printer dialog
</pre>
<p> <a href="qprinter.html#setup">QPrinter::setup</a>() invokes a print dialog, configures the printer
object, and returns TRUE if the user wants to print or FALSE if not.
So we test the return value; if it's TRUE, we...
<p> <pre>            <a href="qmainwindow.html#statusBar">statusBar</a>()-&gt;message( "Printing..." );
</pre>
<p> ... set a statusbar message in case printing takes a while.
<p> <pre>            <a href="qpainter.html">QPainter</a> p;
            if( !p.<a href="qpainter.html#begin">begin</a>( printer ) )               // paint on printer
                return;
</pre>
<p> We create a painter for the output and decide that we wish to paint
on the printer or do nothing at all.
<p> <pre>            p.<a href="qpainter.html#setFont">setFont</a>( e-&gt;<a href="qtextedit.html#font">font</a>() );
            int yPos        = 0;                    // y-position for each line
            <a href="qfontmetrics.html">QFontMetrics</a> fm = p.<a href="qpainter.html#fontMetrics">fontMetrics</a>();
            <a href="qpaintdevicemetrics.html">QPaintDeviceMetrics</a> metrics( printer ); // need width/height
                                                    // of printer surface
</pre>
<p> Then we select the font our <a href="qtextedit.html">QTextEdit</a> object returns as its current
one, and set up some variables we'll need.
<p> <pre>            for( int i = 0 ; i &lt; e-&gt;<a href="qtextedit.html#lines">lines</a>() ; i++ ) {
</pre>
<p> As long as the editing widget contains more lines, we want to print them.
<p> <pre>                if ( Margin + yPos &gt; metrics.<a href="qpaintdevicemetrics.html#height">height</a>() - Margin ) {
</pre>
<p> Before we print a line, we make sure that there is space for it on 
the current page.  If not, we start a new page:
<p> <pre>                    <a href="qstring.html">QString</a> msg( "Printing (page " );
                    msg += QString::<a href="qstring.html#number">number</a>( ++pageNo );
                    msg += ")...";
                    <a href="qmainwindow.html#statusBar">statusBar</a>()-&gt;message( msg );
                    printer-&gt;<a href="qprinter.html#newPage">newPage</a>();             // no more room on this page
                    yPos = 0;                       // back to top of page
</pre>
<p> (Four lines to tell the user what we're doing, two lines to do it.)
<p> <pre>                }
</pre>
<p> Now we know that there's space for the current line ...
<p> <pre>                p.<a href="qpainter.html#drawText">drawText</a>( Margin, Margin + yPos,
                            metrics.<a href="qpaintdevicemetrics.html#width">width</a>(), fm.<a href="qfontmetrics.html#lineSpacing">lineSpacing</a>(),
                            ExpandTabs | DontClip,
                            e-&gt;<a href="qtextedit.html#text">text</a>( i ) );
</pre>
<p> ... and we use the painter to print it. 
<p> In Qt, output to printers uses the exact same code as output to screen,
pixmaps and picture metafiles.  Therefore, we don't call a <a href="qprinter.html">QPrinter</a>
function to draw text, but a <a href="qpainter.html">QPainter</a> function.  QPainter works on all the
output devices mentioned and has a device independent API.  Most of its
code is device independent, too, therefore it is less likely that your
application will have odd bugs.  (If the same code is used to print and to
draw on the screen, it's less likely that you'll have print-only or
screen-only bugs.)
<p> <pre>                yPos = yPos + fm.<a href="qfontmetrics.html#lineSpacing">lineSpacing</a>();
</pre>
<p> With this line, we keep count of how much of the paper we've used
so far.
<p> <pre>            }
            p.<a href="qpainter.html#end">end</a>();                                // send job to printer
</pre>
<p> At this point we've printed all of the text in the editing widget 
and told the printer to finish off the last page. 
<p> <pre>            <a href="qmainwindow.html#statusBar">statusBar</a>()-&gt;message( "Printing completed", 2000 );
</pre>
<p> Finally the user receives the message that we're done.
<p> <pre>        } else {
            <a href="qmainwindow.html#statusBar">statusBar</a>()-&gt;message( "Printing aborted", 2000 );
        }
</pre>
<p> If the user did not want to print (and <a href="qprinter.html#setup">QPrinter::setup</a>() returned
FALSE), we inform him or her about it.
<p> <pre>    }
</pre>
<p> With this little effort we have printed a text document.
So let's care about what happens when a user wishes to <em>close()</em>
an <em>ApplicationWindow</em>.
<p> <a name="closeEvent"></a>
<pre>    void ApplicationWindow::<a href="qwidget.html#closeEvent">closeEvent</a>( <a href="qcloseevent.html">QCloseEvent</a>* ce )
    {
</pre>
<p> This event gets to process window system close events.  A close event is
subtly different from a hide event: hide often means "iconify" whereas
close means that the window is going away for good.
<p> <pre>        if ( !e-&gt;<a href="qtextedit.html#isModified">isModified</a>() ) {
            ce-&gt;<a href="qcloseevent.html#accept">accept</a>();
            return;
        }
</pre>
<p> If the text hasn't been edited, we just accept the event.  The window
will be closed, and because we used the <em>WDestructiveClose</em> widget
flag in the <a href="#ApplicationWindow">&#92;e ApplicationWindow() constructor</a>, 
the widget will be deleted.
<p> <pre>        switch( QMessageBox::<a href="qmessagebox.html#information">information</a>( this, "Qt Application Example",
                                          "Do you want to save the changes"
                                          " to the document?",
                                          "Yes", "No", "Cancel",
                                          0, 1 ) ) {
</pre>
<p> Otherwise we ask the user: What do you want
to do?  
<p> <pre>        case 0:
            save();
            ce-&gt;<a href="qcloseevent.html#accept">accept</a>();
            break;
</pre>
<p> If he/she wants to save and then exit, we do that.  
<p> <pre>        case 1:
            ce-&gt;<a href="qcloseevent.html#accept">accept</a>();
            break;
</pre>
<p> If the user however doesn't want to exit, we ignore the close event (there
is a chance that we can't block it but we try).
<p> <pre>        case 2:
        default: // just for sanity
            ce-&gt;<a href="qcloseevent.html#ignore">ignore</a>();
            break;
</pre>
<p> The last case -- the user wants to abandon the edits and exit -- is very
simple.
<p> <pre>        }
    }
</pre>
<p> Last but not least we implement the slots used by the help menu entries.
<p> <pre>    void ApplicationWindow::about()
    {
        QMessageBox::<a href="qmessagebox.html#about">about</a>( this, "Qt Application Example",
                            "This example demonstrates simple use of "
                            "QMainWindow,\nQMenuBar and QToolBar.");
    }

    void ApplicationWindow::aboutQt()
    {
        QMessageBox::<a href="qmessagebox.html#aboutQt">aboutQt</a>( this, "Qt Application Example" );
    }
</pre>
<p> These two slots use ready-made "about" functions to provide some
information about this program and the GUI toolkit it uses.  (Although you
don't need to provide an About Qt in your programs, if you use Qt for free
we would appreciate it if you tell people what you're using.)
<p> That was all we needed to write a complete, almost useful application with
nice help-functions, almost as good as the "editors" some computer vendors
ship with their desktops, in less than 300 lines of code. As we promised -
a simple application.
<p> <p>See also <a href="step-by-step-examples.html">Step-by-step Examples</a>.

<!-- eof -->
<p><address><hr><div align=center>
<table width=100% cellspacing=0 border=0><tr>
<td>Copyright &copy; 2001 
<a href="http://www.trolltech.com">Trolltech</a><td><a href="http://www.trolltech.com/trademarks.html">Trademarks</a>
<td align=right><div align=right>Qt version 3.0.2</div>
</table></div></address></body>
</html>