Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Fonctions  · 

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.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 94
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 42
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 6
Page suivante

Le Qt Quarterly au hasard

Logo

Requête de données génériques avec QtXmlPatterns et XQuery

Qt Quarterly est la revue trimestrielle proposée par Nokia et à destination des développeurs Qt. Ces articles d'une grande qualité technique sont rédigés par des experts Qt. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt 3.0
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web