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  ·  Tous les espaces de nom  ·  Toutes les classes  ·  Classes principales  ·  Annotées  ·  Classes groupées  ·  Modules  ·  Fonctions  · 

Colliding Mice Example

Files:

The Colliding Mice example shows how to use the Graphics View framework to implement animated items and detect collision between items.

Graphics View provides the QGraphicsScene class for managing and interacting with a large number of custom-made 2D graphical items derived from the QGraphicsItem class, and a QGraphicsView widget for visualizing the items, with support for zooming and rotation.

The example consists of an item class and a main function: the Mouse class represents the individual mice extending QGraphicsItem, and the main() function provides the main application window.

We will first review the Mouse class to see how to animate items and detect item collision, and then we will review the main() function to see how to put the items into a scene and how to implement the corresponding view.

Mouse Class Definition

The mouse class inherits both QObject and QGraphicsItem. The QGraphicsItem class is the base class for all graphical items in the Graphics View framework, and provides a light-weight foundation for writing your own custom items.

 class Mouse : public QObject, public QGraphicsItem
 {
     Q_OBJECT

 public:
     Mouse();

     QRectF boundingRect() const;
     QPainterPath shape() const;
     void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
                QWidget *widget);

 protected:
     void timerEvent(QTimerEvent *event);

 private:
     qreal angle;
     qreal speed;
     qreal mouseEyeDirection;
     QColor color;
 };

When writing a custom graphics item, you must implement QGraphicsItem's two pure virtual public functions: boundingRect(), which returns an estimate of the area painted by the item, and paint(), which implements the actual painting. In addition, we reimplement the shape() function to return an accurate shape of our mouse item; the default implementation simply returns the item's bounding rectangle.

The rationale for deriving from QObject in addition to QGraphicsItem is to be able to animate our items by reimplementing QObject's timerEvent() function and use QObject::startTimer() to generate timer events.

Mouse Class Definition

When constructing a mouse item, we first ensure that all the item's private variables are properly initialized:

 Mouse::Mouse()
     : angle(0), speed(0), mouseEyeDirection(0),
       color(qrand() % 256, qrand() % 256, qrand() % 256)
 {
     rotate(qrand() % (360 * 16));
     startTimer(1000 / 33);
 }

To calculate the various components of the mouse's color, we use the global qrand() function which is a thread-safe version of the standard C++ rand() function.

Then we call the rotate() function inherited from QGraphicsItem. Items live in their own local coordinate system. Their coordinates are usually centered around (0, 0), and this is also the center for all transformations. By calling the item's rotate() function we alter the direction in which the mouse will start moving.

In the end we call QObject's startTimer() function, emitting a timer event every 1000/33 millisecond. This enables us to animate our mouse item using our reimplementation of the timerEvent() function; whenever a mouse receives a timer event it will trigger timerEvent():

 void Mouse::timerEvent(QTimerEvent *)
 {
     QLineF lineToCenter(QPointF(0, 0), mapFromScene(0, 0));
     if (lineToCenter.length() > 150) {
         qreal angleToCenter = ::acos(lineToCenter.dx() / lineToCenter.length());
         if (lineToCenter.dy() < 0)
             angleToCenter = TwoPi - angleToCenter;
         angleToCenter = normalizeAngle((Pi - angleToCenter) + Pi / 2);

         if (angleToCenter < Pi && angleToCenter > Pi / 4) {
             // Rotate left
             angle += (angle < -Pi / 2) ? 0.25 : -0.25;
         } else if (angleToCenter >= Pi && angleToCenter < (Pi + Pi / 2 + Pi / 4)) {
             // Rotate right
             angle += (angle < Pi / 2) ? 0.25 : -0.25;
         }
     } else if (::sin(angle) < 0) {
         angle += 0.25;
     } else if (::sin(angle) > 0) {
         angle -= 0.25;
     }

First we ensure that the mice stays within a circle with a radius of 150 pixels.

Note the mapFromScene() function provided by QGraphicsItem. This function maps a position given in scene coordinates, to the item's coordinate system.

     QList<QGraphicsItem *> dangerMice = scene()->items(QPolygonF()
                                                        << mapToScene(0, 0)
                                                        << mapToScene(-30, -50)
                                                        << mapToScene(30, -50));
     foreach (QGraphicsItem *item, dangerMice) {
         if (item == this)
             continue;

         QLineF lineToMouse(QPointF(0, 0), mapFromItem(item, 0, 0));
         qreal angleToMouse = ::acos(lineToMouse.dx() / lineToMouse.length());
         if (lineToMouse.dy() < 0)
             angleToMouse = TwoPi - angleToMouse;
         angleToMouse = normalizeAngle((Pi - angleToMouse) + Pi / 2);

         if (angleToMouse >= 0 && angleToMouse < Pi / 2) {
             // Rotate right
             angle += 0.5;
         } else if (angleToMouse <= TwoPi && angleToMouse > (TwoPi - Pi / 2)) {
             // Rotate left
             angle -= 0.5;
         }
     }

     if (dangerMice.size() > 1 && (qrand() % 10) == 0) {
         if (qrand() % 1)
             angle += (qrand() % 100) / 500.0;
         else
             angle -= (qrand() % 100) / 500.0;
     }

Then we try to avoid colliding with other mice.

     speed += (-50 + qrand() % 100) / 100.0;

     qreal dx = ::sin(angle) * 10;
     mouseEyeDirection = (qAbs(dx / 5) < 1) ? 0 : dx / 5;

     rotate(dx);
     setPos(mapToParent(0, -(3 + sin(speed) * 3)));
 }

Finally, we calculate the mouse's speed and its eye direction (for use when painting the mouse), and set its new position.

The position of an item describes its origin (local coordinate (0, 0)) in the parent coordinates. The QGraphicsItem::setPos() function sets the position of the item to the given position in the parent's coordinate system. For items with no parent, the given position is interpreted as scene coordinates. QGraphicsItem also provides a mapToParent() function to map a position given in item coordinates, to the parent's coordinate system. If the item has no parent, the position will be mapped to the scene's coordinate system instead.

Then it is time to provide an implementation for the pure virtual functions inherited from QGraphicsItem. Let's first take a look at the boundingRect() function:

 QRectF Mouse::boundingRect() const
 {
     qreal adjust = 0.5;
     return QRectF(-18 - adjust, -22 - adjust,
                   36 + adjust, 60 + adjust);
 }

The boundingRect() function defines the outer bounds of the item as a rectangle. Note that the Graphics View framework uses the bounding rectangle to determine whether the item requires redrawing, so all painting must be restricted inside this rectangle.

 void Mouse::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
 {
     // Body
     painter->setBrush(color);
     painter->drawEllipse(-10, -20, 20, 40);

     // Eyes
     painter->setBrush(Qt::white);
     painter->drawEllipse(-10, -17, 8, 8);
     painter->drawEllipse(2, -17, 8, 8);

     // Nose
     painter->setBrush(Qt::black);
     painter->drawEllipse(QRectF(-2, -22, 4, 4));

     // Pupils
     painter->drawEllipse(QRectF(-8.0 + mouseEyeDirection, -17, 4, 4));
     painter->drawEllipse(QRectF(4.0 + mouseEyeDirection, -17, 4, 4));

     // Ears
     painter->setBrush(scene()->collidingItems(this).isEmpty() ? Qt::darkYellow : Qt::red);
     painter->drawEllipse(-17, -12, 16, 16);
     painter->drawEllipse(1, -12, 16, 16);

     // Tail
     QPainterPath path(QPointF(0, 20));
     path.cubicTo(-5, 22, -5, 22, 0, 25);
     path.cubicTo(5, 27, 5, 32, 0, 30);
     path.cubicTo(-5, 32, -5, 42, 0, 35);
     painter->setBrush(Qt::NoBrush);
     painter->drawPath(path);
 }

The Graphics View framework calls the paint() function to paint the contents of the item; the function paints the item in local coordinates.

Note the painting of the ears: Whenever a mouse item collides with other mice items its ears are filled with red; otherwise they are filled with dark yellow. We use the QGraphicsScene::collidingItems() function to check if there are any colliding mice. The actual collision detection is handled by the Graphics View framework using shape-shape intersection. All we have to do is to ensure that the QGraphicsItem::shape() function returns an accurate shape for our item:

 QPainterPath Mouse::shape() const
 {
     QPainterPath path;
     path.addRect(-10, -20, 20, 40);
     return path;
 }

Because the complexity of arbitrary shape-shape intersection grows with an order of magnitude when the shapes are complex, this operation can be noticably time consuming. An alternative approach is to reimplement the collidesWithItem() function to provide your own custom item and shape collision algorithm.

This completes the Mouse class implementation, it is now ready for use. Let's take a look at the main() function to see how to implement a scene for the mice and a view for displaying the contents of the scene.

The Main() Function

In this example we have chosen to let the main() function provide the main application window, creating the items and the scene, putting the items into the scene and creating a corresponding view.

 int main(int argc, char **argv)
 {
     QApplication app(argc, argv);
     qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));

First, we create an application object and call the global qsrand() function to specify the seed used to generate a new random number sequence of pseudo random integers with the previously mentioned qrand() function.

Then it is time to create the scene:

     QGraphicsScene scene;
     scene.setSceneRect(-300, -300, 600, 600);

The QGraphicsScene class serves as a container for QGraphicsItems. It also provides functionality that lets you efficiently determine the location of items as well as determining which items that are visible within an arbitrary area on the scene.

When creating a scene it is recommended to set the scene's rectangle, i.e., the rectangle that defines the extent of the scene. It is primarily used by QGraphicsView to determine the view's default scrollable area, and by QGraphicsScene to manage item indexing. If not explicitly set, the scene's default rectangle will be the largest bounding rectangle of all the items on the scene since the scene was created (i.e., the rectangle will grow when items are added or moved in the scene, but it will never shrink).

     scene.setItemIndexMethod(QGraphicsScene::NoIndex);

The item index function is used to speed up item discovery. NoIndex implies that item location is of linear complexity, as all items on the scene are searched. Adding, moving and removing items, however, is done in constant time. This approach is ideal for dynamic scenes, where many items are added, moved or removed continuously. The alternative is BspTreeIndex which makes use of binary search resulting in item location algorithms that are of an order closer to logarithmic complexity.

     for (int i = 0; i < MouseCount; ++i) {
         Mouse *mouse = new Mouse;
         mouse->setPos(::sin((i * 6.28) / MouseCount) * 200,
                       ::cos((i * 6.28) / MouseCount) * 200);
         scene.addItem(mouse);
     }

Then we add the mice to the scene.

     QGraphicsView view(&scene);
     view.setRenderHint(QPainter::Antialiasing);
     view.setBackgroundBrush(QPixmap(":/images/cheese.jpg"));

To be able to view the scene we must also create a QGraphicsView widget. The QGraphicsView class visualizes the contents of a scene in a scrollable viewport. We also ensure that the contents is rendered using antialiasing, and we create the cheese background by setting the view's background brush.

The image used for the background is stored as a binary file in the application's executable using Qt's resource system. The QPixmap constructor accepts both file names that refer to actual files on disk and file names that refer to the application's embedded resources.

     view.setCacheMode(QGraphicsView::CacheBackground);
     view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
     view.setDragMode(QGraphicsView::ScrollHandDrag);

Then we set the cache mode; QGraphicsView can cache pre-rendered content in a pixmap, which is then drawn onto the viewport. The purpose of such caching is to speed up the total rendering time for areas that are slow to render, e.g., texture, gradient and alpha blended backgrounds. The CacheMode property holds which parts of the view that are cached, and the CacheBackground flag enables caching of the view's background.

By setting the dragMode property we define what should happen when the user clicks on the scene background and drags the mouse. The ScrollHandDrag flag makes the cursor change into a pointing hand, and dragging the mouse around will scroll the scrollbars.

     view.setWindowTitle(QT_TRANSLATE_NOOP(QGraphicsView, "Colliding Mice"));
     view.resize(400, 300);
     view.show();

     return app.exec();
 }

In the end, we set the application window's title and size before we enter the main event loop using the QApplication::exec() function.

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 44
  2. Microsoft ouvre aux autres compilateurs C++ AMP, la spécification pour la conception d'applications parallèles C++ utilisant le GPU 22
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. RIM : « 13 % des développeurs ont gagné plus de 100 000 $ sur l'AppWord », Qt et open-source au menu du BlackBerry DevCon Europe 0
  5. BlackBerry 10 : premières images du prochain OS de RIM qui devrait intégrer des widgets et des tuiles inspirées de Windows Phone 0
  6. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  7. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
Page suivante

Le blog Digia au hasard

Logo

Déploiement d'applications Qt Commercial sur les tablettes Windows 8

Le blog Digia est l'endroit privilégié pour la communication sur l'édition commerciale de Qt, où des réponses publiques sont apportées aux questions les plus posées au support. 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 4.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