| Classes - Annotated - Tree - Functions - Home - Structure

# Walkthrough: A Simple Application

This walkthrough shows simple use of QMainWindow, QMenuBar, QPopupMenu, QToolBar and QStatusBar - the classes that every modern application window tends to use.

It further shows some use of QWhatsThis (for simple help) and a typical main() using QApplication.

Finally, it shows a typical printout function that uses QPrinter.

## The declaration of ApplicationWindow

Here's the header file in full:

    /****************************************************************************
    ** $Id: qt/examples/application/application.h   2.3.7   edited 2001-01-26 $
    **
    ** 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 <qmainwindow.h>

    class QMultiLineEdit;
    class QToolBar;
    class QPopupMenu;

    class ApplicationWindow: public QMainWindow
    {
        Q_OBJECT
    public:
        ApplicationWindow();
        ~ApplicationWindow();

    protected:
        void closeEvent( QCloseEvent* );

    private slots:
        void newDoc();
        void load();
        void load( const char *fileName );
        void save();
        void saveAs();
        void print();

        void about();
        void aboutQt();

    private:
        QPrinter *printer;
        QMultiLineEdit *e;
        QToolBar *fileTools;
        QString filename;
    };

    #endif

There's nothing much particular about this. It declares a class that inherits QMainWindow, with some slots and some private variables. And it uses a class predeclarations to speed up compiles: `QMultiLineEdit,` `QToolBar` and `QPopupMenu` are declared, not included. make depend then won't think that every .cpp file that includes application.h needs to be recompiled when e.g. qpopupmenu.h changes.

## The simple main()

Here's examples/main.cpp, in full.

    /****************************************************************************
    ** $Id: qt/examples/application/main.cpp   2.3.7   edited 2001-06-12 $
    **
    ** 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 <qapplication.h>
    #include "application.h"

    int main( int argc, char ** argv ) {
        QApplication a( argc, argv );
        ApplicationWindow * mw = new ApplicationWindow();
        mw->setCaption( "Qt Example - Application" );
        mw->show();
        a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );
        return a.exec();
    }

We'll go over main() in detail.

        int main( int argc, char ** argv ) {
            QApplication a( argc, argv );

We create a QApplication object with the usual constructor and let it parse argc and argv so that on X11, this program behaves as X programs are expected to.

            ApplicationWindow * mw = new ApplicationWindow();
            mw->setCaption( "Qt Example - Application" );
            mw->show();

We create an ApplicationWindow as a top-level widget, set its window system caption to "Document 1", and show() it.

            a.connect( &a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()) );

When the application's last window is closed, it should quit.

            return a.exec();

Having completed the application initialization, we start the main event loop (the GUI), and eventually return the error code QApplication returns when it leaves the event loop. (QApplication::exit() lets any part of the program set this code in a way that doesn't prohibit an orderly closedown.)

        }

## The implementation of ApplicationWindow

Since the implementation is much larger (almost 200 lines) we won't include it in full but instead include bits and pieces as necessary. We skip the preliminary #include and some text constants, and start with the constructor.

        ApplicationWindow::ApplicationWindow()
            : QMainWindow( 0, "example application main window", WDestructiveClose )
        {

ApplicationWindow inherits QMainWindow, the Qt class that provides typical application main windows, with menu bars, tool bars, etc.

            int id;

            printer = new QPrinter;

The application example can print things, and we chose to have a QPrinter object lying around so that when the user changes a setting during one printing, the new setting will be the default next time.

            QPixmap openIcon, saveIcon, printIcon;

This example is simple enough to have just three commands. These variables are used to hold the icons for each of them.

            fileTools = new QToolBar( this, "file operations" );

We create a tool bar in this window for putting some tools in.

            fileTools->setLabel( tr( "File Operations" ) );

            openIcon = QPixmap( fileopen );
            QToolButton * fileOpen
                = new QToolButton( openIcon, "Open File", QString::null,
                                   this, SLOT(load()), fileTools, "open file" );

            saveIcon = QPixmap( filesave );
            QToolButton * fileSave
                = new QToolButton( saveIcon, "Save File", QString::null,
                                   this, SLOT(save()), fileTools, "save file" );

            printIcon = QPixmap( fileprint );
            QToolButton * filePrint
                = new QToolButton( printIcon, "Print File", QString::null,
                                   this, SLOT(print()), fileTools, "print file" );

And then we create three tool buttons in that tool bar, each with the appropriate icons and tool-tip text. The three buttons are connected to slots in this object, for example the "Print File" button is connected to ApplicationWindow::print().

            (void)QWhatsThis::whatsThisButton( fileTools );

Then we create a fourth button in the toolbar: A special button that provides "What's This?" help. This must be set up using a special function, as its mouse interface needs to be a little unusual.

            QWhatsThis::add( fileOpen, fileOpenText );
            QMimeSourceFactory::defaultFactory()->setPixmap( "fileopen", openIcon );
            QWhatsThis::add( fileSave, fileSaveText );
            QWhatsThis::add( filePrint, filePrintText );

We add What's This? help for each of the three buttons, and tell the QML engine that when a help text wants the "fileopen" image, it should use the pixmap we've defined.

            QPopupMenu * file = new QPopupMenu( this );
            menuBar()->insertItem( "&File", file );

            file->insertItem( "&New", this, SLOT(newDoc()), CTRL+Key_N );

            id = file->insertItem( openIcon, "&Open",
                                   this, SLOT(load()), CTRL+Key_O );
            file->setWhatsThis( id, fileOpenText );

            id = file->insertItem( saveIcon, "&Save",
                                   this, SLOT(save()), CTRL+Key_S );
            file->setWhatsThis( id, fileSaveText );
            id = file->insertItem( "Save &as...", this, SLOT(saveAs()) );
            file->setWhatsThis( id, fileSaveText );
            file->insertSeparator();
            id = file->insertItem( printIcon, "&Print",
                                   this, SLOT(print()), CTRL+Key_P );
            file->setWhatsThis( id, filePrintText );
            file->insertSeparator();
            file->insertItem( "&Close", this, SLOT(close()), CTRL+Key_W );
            file->insertItem( "&Quit", qApp, SLOT( closeAllWindows() ), CTRL+Key_Q );

We create a QPopupMenu item for the File menu, add it to the menu bar, populate it with three commands, and set What's This? help for them.

Note in particular how What's This? help and pixmaps are used in both the toolbar (above) and the menu bar (here).

            QPopupMenu * help = new QPopupMenu( this );
            menuBar()->insertSeparator();
            menuBar()->insertItem( "&Help", help );

            help->insertItem( "&About", this, SLOT(about()), Key_F1 );
            help->insertItem( "About &Qt", this, SLOT(aboutQt()) );
            help->insertSeparator();
            help->insertItem( "What's &This", this, SLOT(whatsThis()), SHIFT+Key_F1 );

We create a Help menu, add it to the menu bar, and insert a few commands in the Help menu.

            e = new QMultiLineEdit( this, "editor" );
            e->setFocus();
            setCentralWidget( e );

We create a multi-line edit widget, set the initial focus to be there, and make it the central widget of this window.

QMainWindow::centralWidget() is the meat: It's what the menu bar, status bar and tool bars are all arranged around. Since this application is an editor, the central widget is a text editing widget :)

            statusBar()->message( "Ready", 2000 );

We make the status bar say "Ready" for two seconds at startup, just to tell the user that this window has finished initialization and can be used.

            resize( 450, 600 );

We provide a nice default size for the new window.

        }

That's it.

        ApplicationWindow::~ApplicationWindow()
        {
            delete printer;
        }

The only thing this widget needs to do in its destructor is delete the printer it created. All the other objects are child widgets, which Qt will delete as appropriate. Simple.

        void ApplicationWindow::newDoc()
        {
            ApplicationWindow *ed = new ApplicationWindow;
            ed->setCaption("Qt Example - Application");
            ed->show();
        }

This slot, connected to the File->New menu item and the "new file" tool button, simply creates a new ApplicationWindow, sets some size and shows it.

        void ApplicationWindow::load()
        {
            QString fn = QFileDialog::getOpenFileName( QString::null, QString::null,
                                                       this);
            if ( !fn.isEmpty() )
                load( fn );
            else
                statusBar()->message( "Loading aborted", 2000 );
        }

This slot is connected to the "load file" menu item and tool button. As you can see, it asks the user for a file name and then either loads that file or gives an error message in the status bar.

(We give an error message in the status bar since that's less bothersome. We could have used a QMessageBox, but since we assume the user will notice that no file was loaded, we just use the status bar, and the user won't need to hit Enter to make some window go away.)

        void ApplicationWindow::load( const char *fileName )
        {
            QFile f( fileName );
            if ( !f.open( IO_ReadOnly ) )
                return;

            e->setAutoUpdate( FALSE );
            e->clear();

            QTextStream t(&f);
            while ( !t.eof() ) {
                QString s = t.readLine();
                e->append( s );
            }
            f.close();

            e->setAutoUpdate( TRUE );
            e->repaint();
            e->setEdited( FALSE );
            setCaption( fileName );
            QString s;
            s.sprintf( "Loaded document %s", fileName );
            statusBar()->message( s, 2000 );
        }

This function loads a file into the editor. It takes care to turn off auto-update of the editor, for faster loading and less flicker. When it's done, it sets the window system caption to the file name and displays a success message for two seconds in the status bar.

        void ApplicationWindow::save()
        {
            if ( filename.isEmpty() ) {
                saveAs();
                return;
            }

            QString text = e->text();
            QFile f( filename );
            if ( !f.open( IO_WriteOnly ) ) {
                statusBar()->message( QString("Could not write to %1").arg(filename),
                                      2000 );
                return;
            }

            QTextStream t( &f );
            t << text;
            f.close();

This function saves the current file. Nothing remarkable in the first part.

            e->setEdited( FALSE );

Tell the editor that the contents haven't been edited since the last save. When the user closes the window, ApplicationWindow may want to ask "Save?".

            setCaption( filename );

It may be that the document was saved under a different name than the caption, so we set the window caption just to be sure.

            statusBar()->message( QString( "File %1 saved" ).arg( filename ), 2000 );
        }

That was all.

        void ApplicationWindow::saveAs()
        {
            QString fn = QFileDialog::getSaveFileName( QString::null, QString::null,
                                                       this );
            if ( !fn.isEmpty() ) {
                filename = fn;
                save();
            } else {
                statusBar()->message( "Saving aborted", 2000 );
            }
        }

This function asks for a new name, saves the document under that name, and implicitly changes the window system caption to the new name.

        void ApplicationWindow::print()
        {
            const int Margin = 10;
            int pageNo = 1;

print() is called by the File->Print menu item and the "print" tool button.

Since we don't want to print to the very edges of the paper, we use a little margin: 10 points. And we keep track of the page count.

            if ( printer->setup(this) ) {               // printer dialog

QPrinter::setup() 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, and if it's TRUE, we...

                statusBar()->message( "Printing..." );

... set a status bar message in case printing takes any time.

                QPainter p;
                if( !p.begin( printer ) )
                    return;                             // paint on printer

                p.setFont( e->font() );
                int yPos        = 0;                    // y position for each line
                QFontMetrics fm = p.fontMetrics();
                QPaintDeviceMetrics metrics( printer ); // need width/height
                                                        // of printer surface

We create a painter for the output, select font, and set up some variables we'll need.

                for( int i = 0 ; i < e->numLines() ; i++ ) {

For each line in the text editing widget, we want to print it.

                    if ( Margin + yPos > metrics.height() - Margin ) {

Before we print each line: Is there space for it on the current page, given the margins we want to use? IF not, we want to start a new page.

                        QString msg( "Printing (page " );
                        msg += QString::number( ++pageNo );
                        msg += ")...";
                        statusBar()->message( msg );
                        printer->newPage();             // no more room on this page
                        yPos = 0;                       // back to top of page

Four lines to tell the user what we're doing, two lines to do it.

                    }

Okay, now we know there's space for this line.

                    p.drawText( Margin, Margin + yPos,
                                metrics.width(), fm.lineSpacing(),
                                ExpandTabs | DontClip,
                                e->textLine( i ) );

Use the painter to print it.

In Qt, output to printer use the exact same code as output to screen, pixmaps and picture metafiles. Therefore, we don't call a QPrinter function to draw text, we call a QPainter function. QPainter works on all the output devices and has a device independent API. Most of its code is device-independent, too, which means that it's less likely that your application will have odd bugs. (If the same code is used to print as to draw on the screen, it's less likely that you'll have printing-only or screen-only bugs.)

                    yPos = yPos + fm.lineSpacing();

Keep count of how much of the paper we've used.

                }

At this point we've printed all of the text in the editing widget.

                p.end();                                // send job to printer
                statusBar()->message( "Printing completed", 2000 );

So we tell the printer to finish off the last page and tell the user that we're done.

            } else {
                statusBar()->message( "Printing aborted", 2000 );
            }

If the user did not want to print (and QPrinter::setup() returned FALSE), we acknowledge that.

        }

Tha's all. We have printed a text document.

        void ApplicationWindow::closeEvent( QCloseEvent* ce )
        {

This event get to process window-system close events. A close event is subtly different from a hide event: hide may often mean "iconify" but close means that the window is going away for good.

            if ( !e->edited() ) {
                ce->accept();
                return;
            }

If the text hasn't been edited, we just accept the event. The window will be closed, and since we used the `WDestructiveClose` widget flag, the widget will be deleted.

            switch( QMessageBox::information( this, "Qt Application Example",
                                              "The document has been changed since "
                                              "the last save.",
                                              "Save Now", "Cancel", "Leave Anyway",
                                              0, 1 ) ) {
            case 0:
                save();
                ce->accept();
                break;
            case 1:
            default: // just for sanity
                ce->ignore();
                break;
            case 2:
                ce->accept();
                break;
            }
        }

We know the text has been edited, so we ask the user: What do you want to do? If the user wants to save and then exit, we do that. If the user wants to not exit, we ignore the close event (there is a chance that we can't block it but we try). If the user just wants to exit, abandoning the edits, that's very simple.

        void ApplicationWindow::about()
        {
            QMessageBox::about( this, "Qt Application Example",
                                "This example demonstrates simple use of "
                                "QMainWindow,\nQMenuBar and QToolBar.");
        }

        void ApplicationWindow::aboutQt()
        {
            QMessageBox::aboutQt( this, "Qt Application Example" );
        }

These two slots use ready-made "about" functions to say a little about this program and the GUI toolkit it uses. (You don't need to provide an About Qt in your programs, but if you use Qt for free we'd appreciate it if you tell people what you're using.)

That's all. A complete, almost useful application with nice help. Almost as good as the "editors" some computer vendors have shipped with their desktops. In less than 300 lines of code.