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

Walkthrough: A Simple Application with Actions

While reading through the implementation of the ApplicationWindow constructor you have maybe asked yourself: "The fileOpen tool-button in the toolbar does exactly the same thing as the File->Open menu-entry. Their "What's this?" help is the same, the icons common, the same slot is connected to both them ... Shouldn't it be possible to save some code and don't invent the wheel twice?"

Indeed, it is. In modern GUI-application programming you will use so called actions to do this. An action collects all the common items (icon, tooltip, menu-entry text, shortcuts, "What's this?" help-text and what to do -- the actual action) together. Whenever this action is required (in the toolbar, as a menu-entry) all the programmer has to do is to insert the action in the respective toolbar or menu. Its appearance (as a tool-button or a menu-entry) is something, the programmer does not has to worry about -- it's obvious from the context.

With the QAction class, Qt provides you with everything you need to use this striking concept. So let's write an ApplicationWindow constructor that makes use of actions.

The ApplicationWindow constructor with Actions

    ApplicationWindow::ApplicationWindow()
        : QMainWindow( 0, "example application main window", WDestructiveClose )
    {
        printer = new QPrinter;

Nothing new so far. But with the next lines...

        QAction * fileNewAction;
        QAction * fileOpenAction;
        QAction * fileSaveAction, * fileSaveAsAction, * filePrintAction;
        QAction * fileCloseAction, * fileQuitAction;

... the difference becomes obvious. Here we define the actions our application is supposed to undertake: it should create a new editor-instance (fileNewAction), open a file, save a file, save it under a different name, print the content of the editor, close an editor window and quit the entire application.

        fileNewAction = new QAction( "New", "&New", CTRL+Key_N, this, "new" );

The first one has the name new and can be reached via the accelerator Ctrl+N. When used as a menu-entry it will provide the entry New and can be reached via the accelerator Alt-N (&N). As we won't set a special tooltip-text, the text New with the accelerator Ctrl+N in brackets will show up when a user holds the mouse over a tool-button and does nothing.

        connect( fileNewAction, SIGNAL( activated() ) , this,
                 SLOT( newDoc() ) );

When the action becomes activated (the user chooses the respective menu-entry or clicks an appropriate tool-button), it connects to the newDoc() slot.

        fileOpenAction = new QAction( "Open File", QPixmap( fileopen ), "&Open",
                                      CTRL+Key_O, this, "open" );
        connect( fileOpenAction, SIGNAL( activated() ) , this, SLOT( choose() ) );

The same way we create an Open File action and connect its activated() signal to the choose() slot. There is however a novelty: the fileOpenAction (unlike fileNewAction) is assigned a pixmap (the one included with the fileopen.xpm file).

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

For the fileOpenAction we want to provide "What's This?" help and therefore define an appropriate rich-text.

        QMimeSourceFactory::defaultFactory()->setPixmap( "fileopen",
                              fileOpenAction->iconSet().pixmap() );

As fileOpenText makes use of a pixmap, we have to inform the rich-text engine that it should provide the pixmap defined for fileOpenAction whenever a rich-text asks for an image-source named fileopen.

The slightly complex procedure to gain the pixmap from the action is due to the fact that a QAction is not simply assigned a pixmap but an entire iconset. A QIconSet provides up to six pixmaps suited for different sizes (large, small) and modes (active, disabled etc.). As we initially fed fileOpenAction with just one pixmap its iconset will be calculated from it automatically.

For simplicity reasons we want the icon in the "What's this?" text to be the same we used in the fileOpenAction constructor. This is done by using QIconSet::pixmap() upon fileOpenAction's iconSet().

        fileOpenAction->setWhatsThis( fileOpenText );

Finally we assign "What's this?" help to the fileOpenAction.

        fileSaveAction = new QAction( "Save File", QPixmap( filesave ),
                                      "&Save", CTRL+Key_S, this, "save" );
        connect( fileSaveAction, SIGNAL( activated() ) , this, SLOT( save() ) );

        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>";
        fileSaveAction->setWhatsThis( fileSaveText );

The same way we create a Save File action with a pixmap, "What's this?" help and the more common items like menu-entry text and accelerator. Note that we don't have to bother with the rich-text engine because the pixmap is not used in fileSaveText. When activated the fileSaveAction will call the save() slot.

        fileSaveAsAction = new QAction( "Save File As", "Save &as", 0,  this,
                                        "save as" );
        connect( fileSaveAsAction, SIGNAL( activated() ) , this,
                 SLOT( saveAs() ) );
        fileSaveAsAction->setWhatsThis( fileSaveText );

For the Save File As action we reuse fileSaveText but do without a pixmap. On activation, this action calls the saveAs() slot.

        filePrintAction = new QAction( "Print File", QPixmap( fileprint ),
                                       "&Print", CTRL+Key_P, this, "print" );
        connect( filePrintAction, SIGNAL( activated() ) , this,
                 SLOT( print() ) );

        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.";
        filePrintAction->setWhatsThis( filePrintText );

The Print File action -- with an activated() signal connected to print() -- looks very much like fileSaveText.

        fileCloseAction = new QAction( "Close", "&Close", CTRL+Key_W, this,
                                       "close" );
        connect( fileCloseAction, SIGNAL( activated() ) , this,
                 SLOT( close() ) );
        fileQuitAction = new QAction( "Quit", "&Quit", CTRL+Key_Q, this,
                                      "quit" );
        connect( fileQuitAction, SIGNAL( activated() ) , qApp,
                 SLOT( closeAllWindows() ) );

For the last two actions, fileCloseAction and fileQuitAction, we do it the easy way: no "What's this?", no pixmaps. Thus we have defined all the actions we need.

The only thing left is to use them as menu- and toolbar-entries.

        // populate a tool bar with some actions

        QToolBar * fileTools = new QToolBar( this, "file operations" );
        fileTools->setLabel( "File Operations" );

First we create a toolbar in this window and define a caption for it.

As actions that weren't assigned a pixmap are quite useless in a toolbar we'll restrict ourselves to three tool-buttons for opening, saving and printing files.

        fileOpenAction->addTo( fileTools );

The first tool-button is easily installed: All we have to do is to add the fileOpenAction to the fileTools toolbar.

        fileSaveAction->addTo( fileTools );
        filePrintAction->addTo( fileTools );

The same easy procedure applies to fileSaveAction and filePrintAction.

        (void)QWhatsThis::whatsThisButton( fileTools );

To provide the user with a means to toggle his or her mouse in "What's this?" mode, we need a fourth icon in the toolbar: the (predefined) "What's this?" button.

        // populate a menu with all actions

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

Next we install the newly created file popup-menu in the menu bar. After we're done with this, we populate the menu ...

        fileNewAction->addTo( file );
        fileOpenAction->addTo( file );
        fileSaveAction->addTo( file );
        fileSaveAsAction->addTo( file );

... with some menu-entries derived from actions, ...

        file->insertSeparator();

... a separator ...

        filePrintAction->addTo( file );
        file->insertSeparator();
        fileCloseAction->addTo( file );
        fileQuitAction->addTo( file );

... and more actions and separators.

The rest of the constructor ...

        menuBar()->insertSeparator();

        // add a help menu

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

        // create and define the central widget

        e = new QTextEdit( this, "editor" );
        e->setFocus();
        setCentralWidget( e );
        statusBar()->message( "Ready", 2000 );

        resize( 450, 600 );
    }

... is exactly the same as in the tool-button and menu-entry version.

See also Step-by-step Examples.


Copyright © 2002 TrolltechTrademarks
Qt version 3.0.4