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  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

Qt Tutorial 11 - Giving It a Shot

Files:

Screenshot of Chapter 11

In this example we introduce a timer to implement animated shooting.

Line by Line Walkthrough

t11/cannonfield.h

The CannonField now has shooting capabilities.

     void shoot();

Calling this slot will make the cannon shoot if a shot is not in the air.

 private slots:
     void moveShot();

This private slot is used to move the shot while it is in the air, using a QTimer.

 private:
     void paintShot(QPainter &painter);

This private function paints the shot.

     QRect shotRect() const;

This private function returns the shot's enclosing rectangle if one is in the air; otherwise the returned rectangle is undefined.

     int timerCount;
     QTimer *autoShootTimer;
     float shootAngle;
     float shootForce;
 };

These private variables contain information that describes the shot. The timerCount keeps track of the time passed since the shot was fired. The shootAngle is the cannon angle and shootForce is the cannon force when the shot was fired.

t11/cannonfield.cpp

 #include <math.h>

We include <math.h> because we need the sin() and cos() functions. (An alternative would be to include the more modern <cmath> header file. Unfortunately, some Unix platforms still don't support these properly.)

 CannonField::CannonField(QWidget *parent)
     : QWidget(parent)
 {
     currentAngle = 45;
     currentForce = 0;
     timerCount = 0;
     autoShootTimer = new QTimer(this);
     connect(autoShootTimer, SIGNAL(timeout()), this, SLOT(moveShot()));
     shootAngle = 0;
     shootForce = 0;
     setPalette(QPalette(QColor(250, 250, 200)));
     setAutoFillBackground(true);
 }

We initialize our new private variables and connect the QTimer::timeout() signal to our moveShot() slot. We'll move the shot every time the timer times out.

 void CannonField::shoot()
 {
     if (autoShootTimer->isActive())
         return;
     timerCount = 0;
     shootAngle = currentAngle;
     shootForce = currentForce;
     autoShootTimer->start(5);
 }

This function shoots a shot unless a shot is in the air. The timerCount is reset to zero. The shootAngle and shootForce variables are set to the current cannon angle and force. Finally, we start the timer.

 void CannonField::moveShot()
 {
     QRegion region = shotRect();
     ++timerCount;

     QRect shotR = shotRect();

     if (shotR.x() > width() || shotR.y() > height()) {
         autoShootTimer->stop();
     } else {
         region = region.unite(shotR);
     }
     update(region);
 }

moveShot() is the slot that moves the shot, called every 5 milliseconds when the QTimer fires.

Its tasks are to compute the new position, update the screen with the shot in the new position, and if necessary, stop the timer.

First we make a QRegion that holds the old shotRect(). A QRegion is capable of holding any sort of region, and we'll use it here to simplify the painting. shotRect() returns the rectangle where the shot is now. It is explained in detail later.

Then we increment the timerCount, which has the effect of moving the shot one step along its trajectory.

Next we fetch the new shot rectangle.

If the shot has moved beyond the right or bottom edge of the widget we stop the timer, or we add the new shotRect() to the QRegion.

Finally, we repaint the QRegion. This will send a single paint event for just the one or two rectangles that need updating.

 void CannonField::paintEvent(QPaintEvent * /* event */)
 {
     QPainter painter(this);

     paintCannon(painter);
     if (autoShootTimer->isActive())
         paintShot(painter);
 }

The paint event function has been simplified since the previous chapter. Most of the logic has been moved to the new paintShot() and paintCannon() functions.

 void CannonField::paintShot(QPainter &painter)
 {
     painter.setPen(Qt::NoPen);
     painter.setBrush(Qt::black);
     painter.drawRect(shotRect());
 }

This private function paints the shot by drawing a black filled rectangle.

We leave out the implementation of paintCannon(); it is the same as the QWidget::paintEvent() reimplementation from the previous chapter.

 QRect CannonField::shotRect() const
 {
     const double gravity = 4;

     double time = timerCount / 20.0;
     double velocity = shootForce;
     double radians = shootAngle * 3.14159265 / 180;

     double velx = velocity * cos(radians);
     double vely = velocity * sin(radians);
     double x0 = (barrelRect.right() + 5) * cos(radians);
     double y0 = (barrelRect.right() + 5) * sin(radians);
     double x = x0 + velx * time;
     double y = y0 + vely * time - 0.5 * gravity * time * time;

     QRect result(0, 0, 6, 6);
     result.moveCenter(QPoint(qRound(x), height() - 1 - qRound(y)));
     return result;
 }

This private function calculates the center point of the shot and returns the enclosing rectangle of the shot. It uses the initial cannon force and angle in addition to timerCount, which increases as time passes.

The formula used is the standard Newtonian formula for frictionless movement in a gravity field. For simplicity, we've chosen to disregard any Einsteinian effects.

We calculate the center point in a coordinate system where y coordinates increase upward. After we have calculated the center point, we construct a QRect with size 6 x 6 and move its center point to the point calculated above. In the same operation we convert the point into the widget's coordinate system (see The Coordinate System).

The qRound() function is an inline function defined in <QtGlobal> (included by all other Qt header files). qRound() rounds a double to the closest integer.

t11/main.cpp

 class MyWidget : public QWidget
 {
 public:
     MyWidget(QWidget *parent = 0);
 };

The only addition is the Shoot button.

     QPushButton *shoot = new QPushButton(tr("&Shoot"));
     shoot->setFont(QFont("Times", 18, QFont::Bold));

In the constructor we create and set up the Shoot button exactly like we did with the Quit button.

     connect(shoot, SIGNAL(clicked()), cannonField, SLOT(shoot()));

Connects the clicked() signal of the Shoot button to the shoot() slot of the CannonField.

Running the Application

The cannon can shoot, but there's nothing to shoot at.

Exercises

Make the shot a filled circle. [Hint: QPainter::drawEllipse() may help.]

Change the color of the cannon when a shot is in the air.

[Previous: Chapter 10] [Qt Tutorial] [Next: Chapter 12]

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 Labs au hasard

Logo

Le moteur de rendu OpenGL

Les Qt Labs sont les laboratoires des développeurs de Qt, où ils peuvent partager des impressions sur le framework, son utilisation, ce que pourrait être son futur. 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 qtextended4.4
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