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  ·  Classes  ·  Annotées  ·  Hiérarchie  ·  Fonctions  ·  Structure  · 

Chapter 9: With Cannon You Can


Screenshot of tutorial nine

In this example, we become graphic, by drawing a cute little blue cannon. Only cannon.cpp differs from the previous chapter.

Line by Line Walk-Through

cannon.cpp

    void CannonField::paintEvent( QPaintEvent * )
    {
        QPainter p( this );

We'll now start to use QPainter in earnest. We create a painter that operates on this widget.

        p.setBrush( blue );

When QPainter fills a rectangle, a circle or something, it fills the shape using its brush. Here, we set it to use a blue brush. (We could also use a pattern.)

        p.setPen( NoPen );

And the edges of what QPainter draws are drawn using the pen. Here we set it to NoPen, meaning that there will be no special edge when we draw something. The blue brush will go all the way to the edges of the things we draw.

        p.translate( 0, rect().bottom() );

The QPainter::translate() function translates the coordinate system of the QPainter, i.e. moves it by an offset. Here we set the (0,0) point to the bottom left corner of the widget. The x and y directions remain unchanged, i.e. all the y coordinates inside the widget are now negative (see The Coordinate System for more information about Qt's coordinate system).

        p.drawPie( QRect(-35, -35, 70, 70), 0, 90*16 );

The drawPie() function draws a pie shape inside the specified rectangle using a start angle and an arc length. The angles are specified in 1/16th of a degree. Zero degrees is at the 3 o'clock position. The drawing direction is counter-clockwise. Here we draw a quarter of a circle in the bottom left corner of the widget. The pie is filled with blue and has no outline.

        p.rotate( -ang );

The QPainter::rotate() function rotates the coordinate system of the QPainter around the origin. The rotation argument is a float given in degrees (not given in 1/16th of a degree as above) and clockwise. Here we rotate the coordinate system ang degrees counter-clockwise.

        p.drawRect( QRect(33, -4, 15, 8) );

The QPainter::drawRect() function draws the specified rectangle. Here we draw the barrel of the cannon.

It can often be difficult to envision the resulting drawing when the coordinate system has been transformed (translated, rotated, scaled or sheared) as above.

In this case, the coordinate system is first translated, then rotated. If the rectangle QRect(33, -4, 15, 8) had been drawn in the translated coordinate system, it would have looked like this:

The cannon, translated but not rotated

Note that the rectangle is clipped by the border of the CannonField widget. When we rotate the coordinate system, for instance 60 degrees, the rectangle will be rotated around (0,0), which is the bottom left corner, since we have translated the coordinate system. The result looks like this:

The cannon, translated and rotated

We're done, except that we haven't explained why Windows didn't dither this time.

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

We tell Qt that we want a different color allocation strategy for this program. There is no single correct color allocation strategy. Since this program uses an unusual yellow but not many colors, CustomColor is best. There are several other allocation strategies. You can read about them in the QApplication::setColorSpec() documentation.

Mostly, you can ignore this - the default is good. Occasionally some applications with unusual color use look bad, and often changing the allocation strategy helps.

Behavior

When the slider is operated, the angle of the drawn cannon changes accordingly.

The Q on the Quit button is now underlined, and Alt-Q does what you think it does. If you do not know why, you didn't do the exercises in chapter eight.

You may notice that the cannon flickers annoyingly, especially on a slow machine. We'll fix this in the next chapter.

Exercises

Set a different pen instead of NoPen. Set a patterned brush.

Try "Q&uit" or "Qu&it" as button text instead of "&Quit" - what happens?

You may now go on to chapter ten.

[Previous tutorial] [Next tutorial] [Main tutorial page]

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 69
  2. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 27
  3. Une nouvelle ère d'IHM 3D pour les automobiles, un concept proposé par Digia et implémenté avec Qt 3
  4. Qt Creator 2.5 est sorti en beta, l'EDI supporte maintenant plus de fonctionnalités de C++11 2
  5. Vingt sociétés montrent leurs décodeurs basés sur Qt au IPTV World Forum, en en exploitant diverses facettes (déclaratif, Web, widgets) 0
  6. PySide devient un add-on Qt et rejoint le Qt Project et le modèle d'open gouvernance 1
  7. Thread travailleur avec Qt en utilisant les signaux et les slots, un article de Christophe Dumez traduit par Thibaut Cuvelier 1
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 101
  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. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 51
  4. «Le projet de loi des droits du développeur» : quelles conditions doivent remplir les entreprises pour que le développeur puisse réussir ? 69
  5. Les développeurs détestent-ils les antivirus ? Un programmeur manifeste sa haine envers ces solutions de sécurité 27
  6. Qt Commercial : Digia organise un webinar gratuit le 27 mars sur la conception d'interfaces utilisateur et d'applications avec le framework 0
  7. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
Page suivante

Le Qt Developer Network au hasard

Logo

Introduction

Le Qt Developer Network est un réseau de développeurs Qt anglophone, où ils peuvent partager leur expérience sur le framework. 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 2.3
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