|  | Home · All Classes · Main Classes · Grouped Classes · Modules · Functions |

[Previous: Chapter 13] [Qt Tutorial]

# Qt Tutorial 14 - Facing the Wall

Files:

- tutorials/tutorial/t14/cannonfield.cpp
- tutorials/tutorial/t14/cannonfield.h
- tutorials/tutorial/t14/gameboard.cpp
- tutorials/tutorial/t14/gameboard.h
- tutorials/tutorial/t14/lcdrange.cpp
- tutorials/tutorial/t14/lcdrange.h
- tutorials/tutorial/t14/main.cpp
- tutorials/tutorial/t14/t14.pro

This is the final example: a complete game.

We add keyboard accelerators and introduce mouse events to `CannonField`. We put a frame around the `CannonField` and add a barrier (wall) to make the game more challenging.

## Line by Line Walkthrough

### t14/cannonfield.h

The `CannonField` can now receive mouse events to make the user aim the barrel by clicking on it and dragging. `CannonField` also has a barrier wall.

     protected:
         void paintEvent(QPaintEvent *event);
         void mousePressEvent(QMouseEvent *event);
         void mouseMoveEvent(QMouseEvent *event);
         void mouseReleaseEvent(QMouseEvent *event);

In addition to the familiar event handlers, `CannonField` implements three mouse event handlers. The names say it all.

         void paintBarrier(QPainter &painter);

This private function paints the barrier wall.

         QRect barrierRect() const;

This private function returns the enclosing rectangle of the barrier.

         bool barrelHit(const QPoint &pos) const;

This private function checks if a point is inside the barrel of the cannon.

         bool barrelPressed;

This private variable is `true` if the user has pressed the mouse on the barrel and not released it.

### t14/cannonfield.cpp

         barrelPressed = false;

This line has been added to the constructor. Initially, the mouse is not pressed on the barrel.

         } else if (shotR.x() > width() || shotR.y() > height()
                    || shotR.intersects(barrierRect())) {

Now that we have a barrier, there are three ways to miss. We test for the third, too.

     void CannonField::mousePressEvent(QMouseEvent *event)
     {
         if (event->button() != Qt::LeftButton)
             return;
         if (barrelHit(event->pos()))
             barrelPressed = true;
     }

This is a Qt event handler. It is called when the user presses a mouse button when the mouse cursor is over the widget.

If the event was not generated by the left mouse button, we return immediately. Otherwise, we check if the position of the mouse cursor is within the cannon's barrel. If it is, we set `barrelPressed` to `true`.

Notice that the QMouseEvent::pos() function returns a point in the widget's coordinate system.

     void CannonField::mouseMoveEvent(QMouseEvent *event)
     {
         if (!barrelPressed)
             return;
         QPoint pos = event->pos();
         if (pos.x() <= 0)
             pos.setX(1);
         if (pos.y() >= height())
             pos.setY(height() - 1);
         double rad = atan(((double)rect().bottom() - pos.y()) / pos.x());
         setAngle(qRound(rad * 180 / 3.14159265));
     }

This is another Qt event handler. It is called when the user already has pressed the mouse button inside this widget and then moves/drags the mouse. (You can make Qt send mouse move events even when no buttons are pressed. See QWidget::setMouseTracking().)

This handler repositions the cannon's barrel according to the position of the mouse cursor.

First, if the barrel is not pressed, we return. Next, we fetch the mouse cursor's position. If the mouse cursor is to the left or below the widget, we adjust the point to be inside the widget.

Then we calculate the angle between the bottom edge of the widget and the imaginary line between the bottom-left corner of the widget and the cursor position. Finally we set the cannon's angle to the new value converted to degrees.

Remember that `setAngle()` redraws the cannon.

     void CannonField::mouseReleaseEvent(QMouseEvent *event)
     {
         if (event->button() == Qt::LeftButton)
             barrelPressed = false;
     }

This Qt event handler is called whenever the user releases a mouse button and it was pressed inside this widget.

If the left button is released, we can be sure that the barrel is no longer pressed.

The paint event has one extra line:

         paintBarrier(painter);

`paintBarrier()` does the same sort of thing as `paintShot()`, `paintTarget()`, and `paintCannon()`.

     void CannonField::paintBarrier(QPainter &painter)
     {
         painter.setPen(Qt::black);
         painter.setBrush(Qt::yellow);
         painter.drawRect(barrierRect());
     }

This private function paints the barrier as a rectangle filled with yellow and with a black outline.

     QRect CannonField::barrierRect() const
     {
         return QRect(145, height() - 100, 15, 99);
     }

This private function returns the rectangle of the barrier. We fix the bottom edge of the barrier to the bottom edge of the widget.

     bool CannonField::barrelHit(const QPoint &pos) const
     {
         QMatrix matrix;
         matrix.translate(0, height());
         matrix.rotate(-currentAngle);
         matrix = matrix.inverted();
         return barrelRect.contains(matrix.map(pos));
     }

This function returns `true` if the point is in the barrel; otherwise it returns `false`.

Here we use the class QMatrix. QMatrix defines a coordinate system mapping. It can perform the same transformations as the QPainter.

Here we perform the same transformation steps as we do when drawing the barrel in the `paintCannon()` function. First we translate the coordinate system and then we rotate it.

Now we need to check whether the point `pos` (in widget coordinates) lies inside the barrel. To do this, we invert the transformation matrix. The inverted matrix performs the inverse transformation that we used when drawing the barrel. We map the point `pos` using the inverted matrix and return `true` if it is inside the original barrel rectangle.

### t14/gameboard.cpp

         QFrame *cannonBox = new QFrame;
         cannonBox->setFrameStyle(QFrame::WinPanel | QFrame::Sunken);

We create and set up a QFrame, and set its frame style. This results in a 3D frame around the `CannonField`.

         (void) new QShortcut(Qt::Key_Enter, this, SLOT(fire()));
         (void) new QShortcut(Qt::Key_Return, this, SLOT(fire()));
         (void) new QShortcut(Qt::CTRL + Qt::Key_Q, this, SLOT(close()));

Here we create and set up three QShortcut objects. These objects intercept keyboard events to a widget and call slots if certain keys are pressed. Note that a QShortcut object is a child of a widget and will be destroyed when that widget is destroyed. QShortcut itself is not a widget and has no visible effect on its parent.

We define three shortcut keys. We want the `fire()` slot to be called when the user presses Enter or Return. We also want the application to quit when key Ctrl+Q is pressed. Instead of connecting to QCoreApplication::quit(), we connect to QWidget::close() this time. Since the `GameBoard` is the application's main widget, this has the same effect as quit().

Qt::CTRL, Qt::Key_Enter, Qt::Key_Return, and Qt::Key_Q are all constants declared in the Qt namespace.

         QVBoxLayout *cannonLayout = new QVBoxLayout;
         cannonLayout->addWidget(cannonField);
         cannonBox->setLayout(cannonLayout);

         QGridLayout *gridLayout = new QGridLayout;
         gridLayout->addWidget(quit, 0, 0);
         gridLayout->addLayout(topLayout, 0, 1);
         gridLayout->addLayout(leftLayout, 1, 0);
         gridLayout->addWidget(cannonBox, 1, 1, 2, 1);
         gridLayout->setColumnStretch(1, 10);
         setLayout(gridLayout);

We give `cannonBox` its own QVBoxLayout, and we add `cannonField` to that layout. This implicitly makes `cannonField` a child of `cannonBox`. Because nothing else is in the box, the effect is that the QVBoxLayout will put a frame around the `CannonField`. We put `cannonBox`, not `cannonField`, in the grid layout.

## Running the Application

The cannon now shoots when you press Enter. You can also position the cannon's angle using the mouse. The barrier makes it a little more challenging to play the game. We also have a nice looking frame around the `CannonField`.

## Exercises

Write a space invaders game.

(This exercise was first done by Igor Rafienko. You can download his game.)

The new exercise is: Write a Breakout game.

Final exhortation: Go forth now and create masterpieces of the programming art!

[Previous: Chapter 13] [Qt Tutorial]