Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

# Walkthrough: A Simple Application

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

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

Finally, it shows a typical printout function based on QPrinter.

## The declaration of ApplicationWindow

Here's the header file in full:

    /****************************************************************************
    ** $Id:  qt/application.h   3.0.0   edited Jun 22 13:24 $
    **
    ** 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 QTextEdit;

    class ApplicationWindow: public QMainWindow
    {
        Q_OBJECT

    public:
        ApplicationWindow();
        ~ApplicationWindow();

    protected:
        void closeEvent( QCloseEvent* );

    private slots:
        void newDoc();
        void choose();
        void load( const QString &fileName );
        void save();
        void saveAs();
        void print();

        void about();
        void aboutQt();

    private:
        QPrinter *printer;
        QTextEdit *e;
        QString filename;
    };

    #endif

It declares a class that inherits QMainWindow, with slots and private variables. The class predeclaration of QTextEdit at the beginning (instead of an include) helps to speed up compiles. With this trick, make depend won't insist on recompiling every .cpp file that includes application.h when qtextedit.h changes.

## A simple main()

Let's first have a look at examples/main.cpp, in full ...

    /****************************************************************************
    ** $Id:  qt/main.cpp   3.0.0   edited Jun 22 13:24 $
    **
    ** 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();
    }

... and go over main() in detail.

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

With the above line, we create a QApplication object with the usual constructor and let it parse argc and argv. QApplication itself takes care of X11-specific command-line options like -geometry, thus the program automatically behaves the way X clients 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. Both, the signal and the slot are predefined members of QApplication.

            return a.exec();

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.

        }

## The Implementation of ApplicationWindow

Since the implementation is quite large (almost 300 lines) we won't bore you with the preliminary headerfile #includes. Before we start with the constructor there are however three #include lines worth mentioning:

        #include "filesave.xpm"
        #include "fileopen.xpm"
        #include "fileprint.xpm"

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.

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

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

            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;

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.

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

We create a toolbar in this window ...

            fileTools->setLabel( "File Operations" );

... 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.

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

Now we create the first tool button for the fileTools toolbar with the appropriate icon and the tool-tip text "Open File". The fileopen.xpm we included at the beginning contains the definition of a pixmap named fileopen. This we use as the icon to illustrate our first tool button.

            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" );

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 ApplicationWindow::print().

            (void)QWhatsThis::whatsThisButton( fileTools );

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.

            const char * fileOpenText = "<p><img source=\"fileopen\"> "
                         "Click this button to open a <em>new file</em>. <br>"
                         "You can also select the <b>Open</b> command "
                         "from the <b>File</b> menu.</p>";

            QWhatsThis::add( fileOpen, fileOpenText );

With the above line we add the "What's This?" help-text to the fileOpen button...

            QMimeSourceFactory::defaultFactory()->setPixmap( "fileopen", openIcon );

... and tell the rich-text engine that when a help-text (like the one saved in fileOpenText) requests an image named "fileopen", the openIcon pixmap is used.

            const char * fileSaveText = "<p>Click this button to save the file you "
                         "are editing. You will be prompted for a file name.\n"
                         "You can also select the <b>Save</b> command "
                         "from the <b>File</b> menu.</p>";

            QWhatsThis::add( 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::add( filePrint, filePrintText );

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 fileSaveText, the entire string must be surrounded by <p> and </p>. In filePrintText, we don't have rich-text elements, so this is not necessary.

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

Next we create a QPopupMenu for the File menu and add it to the menu bar. With the ampersand previous to the letter F, we allow the user to use the shortcut Alt+F to open this menu.

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

Its first entry is connected to the (yet to be implementled) slot newDoc(). When the user chooses this New entry (e.g. via typing the letter N as marked by the ampersand) or uses the Ctrl+N accelerator, a new editor-window will pop up.

            int id;
            id = file->insertItem( openIcon, "&Open...",
                                   this, SLOT(choose()), 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 );

We populate the File menu with three more commands (Open, Save and Save 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).

            file->insertSeparator();

Then we insert a separator, ...

            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 );

... the Print command with "What's This?" help, another separator and two more commands (Close and Quit) without "What's This?" and pixmaps. In case of the Close command, the signal is connected to the close() slot of the respective ApplicationWindow object whilst the Quit command affects the entire application.

Because ApplicationWindow is a QWidget, the close() function triggers a call to closeEvent() which we will implement later.

            menuBar()->insertSeparator();

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.

            QPopupMenu * help = new QPopupMenu( this );
            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. Depending on the style it will appear on the right hand side of the menu bar or not.

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

Now we create a simple text-editor, set the initial focus to it, and make it the central widget of this window.

QMainWindow::centralWidget() 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. :)

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

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.

            resize( 450, 600 );

Finally it's time to resize the new window to a a nice default size.

        }

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 ApplicationWindow constructor is implemented using actions. Here we'll continue with the destructor.

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

The only thing an ApplicationWindow 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.

Now our task is to implement all the slots mentioned in the header file and used in the constructor.

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

This slot, connected to the File->New menu item, simply creates a new ApplicationWindow and shows it.

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

The choose() slot is connected to the Open menu item and tool button. With a little help from QFileDialog::getOpenFileName(), it asks the user for a file name and then either loads that file or gives an error message in the statusbar.

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

            QTextStream ts( &f );
            e->setText( ts.read() );
            e->setModified( FALSE );
            setCaption( fileName );
            statusBar()->message( "Loaded document " + fileName, 2000 );
        }

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.

        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();

As its name suggests, this function saves the current file. If no filename has been specified so far, the saveAs() routine is called. Unwritable files cause the ApplicationWindow object to provide an error-message in the statusbar. Note that there are more than one possibilities to achieve this: compare the above statusBar()->message() line with the appropriate code in the load() function.

            e->setModified( FALSE );

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, ApplicationWindow::closeEvent() will ask about it.

            setCaption( filename );

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.

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

With a message in the statusbar, we inform the user that the file was saved successfully.

        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 filePrint tool button.

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.

            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; if it's TRUE, we...

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

... set a statusbar message in case printing takes a while.

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

We create a painter for the output and decide that we wish to paint on the printer or do nothing at all.

                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

Then we select the font our QTextEdit object returns as its current one, and set up some variables we'll need.

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

As long as the editing widget contains more lines, we want to print them.

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

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:

                        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.)

                    }

Now we know that there's space for the current line ...

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

... and we use the painter to print it.

In Qt, output to printers uses the exact same code as output to screen, pixmaps and picture metafiles. Therefore, we don't call a QPrinter function to draw text, but a QPainter 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.)

                    yPos = yPos + fm.lineSpacing();

With this line, we keep count of how much of the paper we've used so far.

                }
                p.end();                                // send job to printer

At this point we've printed all of the text in the editing widget and told the printer to finish off the last page.

                statusBar()->message( "Printing completed", 2000 );

Finally the user receives the message that we're done.

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

If the user did not want to print (and QPrinter::setup() returned FALSE), we inform him or her about it.

        }

With this little effort we have printed a text document. So let's care about what happens when a user wishes to close() an ApplicationWindow.

        void ApplicationWindow::closeEvent( QCloseEvent* ce )
        {

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.

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

If the text hasn't been edited, we just accept the event. The window will be closed, and because we used the WDestructiveClose widget flag in the \e ApplicationWindow() constructor, the widget will be deleted.

            switch( QMessageBox::information( this, "Qt Application Example",
                                              "Do you want to save the changes"
                                              " to the document?",
                                              "Yes", "No", "Cancel",
                                              0, 1 ) ) {

Otherwise we ask the user: What do you want to do?

            case 0:
                save();
                ce->accept();
                break;

If he/she wants to save and then exit, we do that.

            case 1:
                ce->accept();
                break;

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).

            case 2:
            default: // just for sanity
                ce->ignore();
                break;

The last case -- the user wants to abandon the edits and exit -- is very simple.

            }
        }

Last but not least we implement the slots used by the help menu entries.

        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 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.)

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.

See also Step-by-step Examples.