<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- /home/qt/mkdist-qt-4.4.3-1222864207/qt-embedded-linux-opensource-src-4.4.3/doc/src/tutorials/tutorial.qdoc -->
<head>
  <title>Qt 4.4: Qt Tutorial 12 - Hanging in the Air the Way Bricks Don't</title>
  <link rel="prev" href="tutorials-tutorial-t11.html" />
  <link rel="contents" href="tutorials-tutorial.html" />
  <link rel="next" href="tutorials-tutorial-t13.html" />
  <link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" border="0" /></a></td>
<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="namespaces.html"><font color="#004faf">All&nbsp;Namespaces</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"></td></tr></table><p>
[Previous: <a href="tutorials-tutorial-t11.html">Chapter 11</a>]
[<a href="tutorials-tutorial.html">Qt Tutorial</a>]
[Next: <a href="tutorials-tutorial-t13.html">Chapter 13</a>]
</p>
<h1 class="title">Qt Tutorial 12 - Hanging in the Air the Way Bricks Don't<br /><span class="subtitle"></span>
</h1>
<p>Files:</p>
<ul>
<li><a href="tutorials-tutorial-t12-cannonfield-cpp.html">tutorials/tutorial/t12/cannonfield.cpp</a></li>
<li><a href="tutorials-tutorial-t12-cannonfield-h.html">tutorials/tutorial/t12/cannonfield.h</a></li>
<li><a href="tutorials-tutorial-t12-lcdrange-cpp.html">tutorials/tutorial/t12/lcdrange.cpp</a></li>
<li><a href="tutorials-tutorial-t12-lcdrange-h.html">tutorials/tutorial/t12/lcdrange.h</a></li>
<li><a href="tutorials-tutorial-t12-main-cpp.html">tutorials/tutorial/t12/main.cpp</a></li>
<li><a href="tutorials-tutorial-t12-t12-pro.html">tutorials/tutorial/t12/t12.pro</a></li>
</ul>
<p align="center"><img src="images/t12.png" alt="Screenshot of Chapter 12" /></p><p>In this example, we extend our <tt>LCDRange</tt> class to include a text label. We also provide something to shoot at.</p>
<a name="line-by-line-walkthrough"></a>
<h2>Line by Line Walkthrough</h2>
<a name="t12-lcdrange-h"></a>
<h3><a href="tutorials-tutorial-t12-lcdrange-h.html">t12/lcdrange.h</a></h3>
<p>The <tt>LCDRange</tt> now has a text label.</p>
<pre> class QLabel;
 class QSlider;</pre>
<p>We forward declare <a href="qlabel.html">QLabel</a> and <a href="qslider.html">QSlider</a> because we want to use pointers to them in the class definition. We could also use <tt>#include</tt>, but that would slow down compilation for nothing.</p>
<pre> class LCDRange : public QWidget
 {
     Q_OBJECT

 public:
     LCDRange(QWidget *parent = 0);
     LCDRange(const QString &amp;text, QWidget *parent = 0);</pre>
<p>We have added a new constructor that sets the label text in addition to the parent.</p>
<pre>     QString text() const;</pre>
<p>This function returns the label text.</p>
<pre>     void setText(const QString &amp;text);</pre>
<p>This slot sets the label text.</p>
<pre> private:
     void init();</pre>
<p>Because we now have two constructors, we have chosen to put the common initialization in the private <tt>init()</tt> function.</p>
<pre>     QLabel *label;</pre>
<p>We also have a new private variable: a <a href="qlabel.html">QLabel</a>. <a href="qlabel.html">QLabel</a> is one of Qt's standard widgets and can show a text or a <a href="qpixmap.html">QPixmap</a> with or without a frame.</p>
<a name="t12-lcdrange-cpp"></a>
<h3><a href="tutorials-tutorial-t12-lcdrange-cpp.html">t12/lcdrange.cpp</a></h3>
<pre> LCDRange::LCDRange(QWidget *parent)
     : QWidget(parent)
 {
     init();
 }</pre>
<p>This constructor calls the <tt>init()</tt> function, which contains the common initialization code.</p>
<pre> LCDRange::LCDRange(const QString &amp;text, QWidget *parent)
     : QWidget(parent)
 {
     init();
     setText(text);
 }</pre>
<p>This constructor first calls <tt>init()</tt> and then sets the label text.</p>
<pre> void LCDRange::init()
 {
     QLCDNumber *lcd = new QLCDNumber(2);
     lcd-&gt;setSegmentStyle(QLCDNumber::Filled);

     slider = new QSlider(Qt::Horizontal);
     slider-&gt;setRange(0, 99);
     slider-&gt;setValue(0);
     label = new QLabel;
     label-&gt;setAlignment(Qt::AlignHCenter | Qt::AlignTop);

     connect(slider, SIGNAL(valueChanged(int)),
             lcd, SLOT(display(int)));
     connect(slider, SIGNAL(valueChanged(int)),
             this, SIGNAL(valueChanged(int)));

     QVBoxLayout *layout = new QVBoxLayout;
     layout-&gt;addWidget(lcd);
     layout-&gt;addWidget(slider);
     layout-&gt;addWidget(label);
     setLayout(layout);

     setFocusProxy(slider);
 }</pre>
<p>The setup of <tt>lcd</tt> and <tt>slider</tt> is the same as in the previous chapter. Next we create a <a href="qlabel.html">QLabel</a> and tell it to align the contents centered horizontally and to the top vertically. The <a href="qobject.html#connect">QObject::connect</a>() calls have also been taken from the previous chapter.</p>
<pre> QString LCDRange::text() const
 {
     return label-&gt;text();
 }</pre>
<p>This function returns the label text.</p>
<pre> void LCDRange::setText(const QString &amp;text)
 {
     label-&gt;setText(text);
 }</pre>
<p>This function sets the label text.</p>
<a name="t12-cannonfield-h"></a>
<h3><a href="tutorials-tutorial-t12-cannonfield-h.html">t12/cannonfield.h</a></h3>
<p>The <tt>CannonField</tt> now has two new signals: <tt>hit()</tt> and <tt>missed()</tt>. In addition, it contains a target.</p>
<pre>     void newTarget();</pre>
<p>This slot creates a target at a new position.</p>
<pre> signals:
     void hit();
     void missed();</pre>
<p>The <tt>hit()</tt> signal is emitted when a shot hits the target. The <tt>missed()</tt> signal is emitted when the shot moves beyond the right or bottom edge of the widget (i.e&#x2e;, it is certain that it has not and will not hit the target).</p>
<pre>     void paintTarget(QPainter &amp;painter);</pre>
<p>This private function paints the target.</p>
<pre>     QRect targetRect() const;</pre>
<p>This private function returns the enclosing rectangle of the target.</p>
<pre>     QPoint target;</pre>
<p>This private variable contains the center point of the target.</p>
<a name="t12-cannonfield-cpp"></a>
<h3><a href="tutorials-tutorial-t12-cannonfield-cpp.html">t12/cannonfield.cpp</a></h3>
<pre> #include &lt;stdlib.h&gt;</pre>
<p>We include the <tt>&lt;stdlib.h&gt;</tt> header file because we need the <tt>qrand()</tt> function.</p>
<pre>     newTarget();</pre>
<p>This line has been added to the constructor. It creates a &quot;random&quot; position for the target. In fact, the <tt>newTarget()</tt> function will try to paint the target. Because we are in a constructor, the <tt>CannonField</tt> widget is invisible. Qt guarantees that no harm is done when calling <a href="qwidget.html#update">QWidget::update</a>() on a hidden widget.</p>
<pre> void CannonField::newTarget()
 {
     static bool firstTime = true;

     if (firstTime) {
         firstTime = false;
         QTime midnight(0, 0, 0);
         qsrand(midnight.secsTo(QTime::currentTime()));
     }
     target = QPoint(200 + qrand() % 190, 10 + qrand() % 255);
     update();
 }</pre>
<p>This private function creates a target center point at a new random position.</p>
<p>We use the <tt>qrand()</tt> function to fetch random integers. The <tt>qrand()</tt> function normally returns the same series of numbers each time you run a program. This would make the target appear at the same position every time. To avoid this, we must set a random seed the first time this function is called. The random seed must also be random in order to avoid equal random number series. The solution is to use the number of seconds that have passed since midnight as a pseudo-random value.</p>
<p>First we create a static <tt>bool</tt> local variable. A static variable like this one is guaranteed to keep its value between calls to the function.</p>
<p>The <tt>if</tt> test will succeed only the first time this function is called because we set <tt>firstTime</tt> to <tt>false</tt> inside the <tt>if</tt> block.</p>
<p>Then we create the <a href="qtime.html">QTime</a> object <tt>midnight</tt>, which represents the time 00:00:00. Next we fetch the number of seconds from midnight until now and use it as a random seed. See the documentation for <a href="qdate.html">QDate</a>, <a href="qtime.html">QTime</a>, and <a href="qdatetime.html">QDateTime</a> for more information.</p>
<p>Finally we calculate the target's center point. We keep it within the rectangle (<i>x</i> = 200, <i>y</i> = 35, <i>width</i> = 190, <i>height</i> = 255), i.e&#x2e;, the possible <i>x</i> and <i>y</i> values are 200 to 389 and 35 to 289, respectively) in a coordinate system where we put <i>y</i> position 0 at the bottom edge of the widget and let <i>y</i> values increase upwards <i>x</i> is as normal, with 0 at the left edge and with <i>x</i> values increasing to the right.</p>
<p>By experimentation we have found this to always be in reach of the shot.</p>
<pre> void CannonField::moveShot()
 {
     QRegion region = shotRect();
     ++timerCount;

     QRect shotR = shotRect();</pre>
<p>This part of the timer event has not changed from the previous chapter.</p>
<pre>     if (shotR.intersects(targetRect())) {
         autoShootTimer-&gt;stop();
         emit hit();</pre>
<p>This <tt>if</tt> statement checks whether the shot rectangle intersects the target rectangle. If it does, the shot has hit the target (ouch!). We stop the shoot timer and emit the <tt>hit()</tt> signal to tell the outside world that a target was destroyed, and return.</p>
<p>Note that we could have created a new target on the spot, but because the <tt>CannonField</tt> is a component we leave such decisions to the user of the component.</p>
<pre>     } else if (shotR.x() &gt; width() || shotR.y() &gt; height()) {
         autoShootTimer-&gt;stop();
         emit missed();</pre>
<p>This <tt>if</tt> statement is the same as in the previous chapter, except that it now emits the <tt>missed()</tt> signal to tell the outside world about the failure.</p>
<pre>     } else {
         region = region.unite(shotR);
     }
     update(region);
 }</pre>
<p>And the rest of the function is as before.</p>
<p><tt>CannonField::paintEvent()</tt> is as before, except that this has been added:</p>
<pre>     paintTarget(painter);</pre>
<p>This line makes sure that the target is also painted when necessary.</p>
<pre> void CannonField::paintTarget(QPainter &amp;painter)
 {
     painter.setPen(Qt::black);
     painter.setBrush(Qt::red);
     painter.drawRect(targetRect());
 }</pre>
<p>This private function paints the target; a rectangle filled with red and with a black outline.</p>
<pre> QRect CannonField::targetRect() const
 {
     QRect result(0, 0, 20, 10);
     result.moveCenter(QPoint(target.x(), height() - 1 - target.y()));
     return result;
 }</pre>
<p>This private function returns the enclosing rectangle of the target. Remember from <tt>newTarget()</tt> that the <tt>target</tt> point uses <i>y</i> coordinate 0 at the bottom of the widget. We calculate the point in widget coordinates before we call <a href="qrect.html#moveCenter">QRect::moveCenter</a>().</p>
<p>The reason we have chosen this coordinate mapping is to fix the distance between the target and the bottom of the widget. Remember that the widget can be resized by the user or the program at any time.</p>
<a name="t12-main-cpp"></a>
<h3><a href="tutorials-tutorial-t12-main-cpp.html">t12/main.cpp</a></h3>
<p>There are no new members in the <tt>MyWidget</tt> class, but we have slightly changed the constructor to set the new <tt>LCDRange</tt> text labels.</p>
<pre>     LCDRange *angle = new LCDRange(tr(&quot;ANGLE&quot;));</pre>
<p>We set the angle text label to &quot;ANGLE&quot;.</p>
<pre>     LCDRange *force = new LCDRange(tr(&quot;FORCE&quot;));</pre>
<p>We set the force text label to &quot;FORCE&quot;.</p>
<a name="running-the-application"></a>
<h2>Running the Application</h2>
<p>The <tt>LCDRange</tt> widgets look a bit strange: When resizing <tt>MyWidget</tt>, the built-in layout management in <a href="qvboxlayout.html">QVBoxLayout</a> gives the labels too much space and the rest not enough; making the space between the two <tt>LCDRange</tt> widgets change size. We'll fix that in the next chapter.</p>
<a name="exercises"></a>
<h2>Exercises</h2>
<p>Make a cheat button that, when pressed, makes the <tt>CannonField</tt> display the shot trajectory for five seconds.</p>
<p>If you did the &quot;round shot&quot; exercise from the previous chapter, try changing the <tt>shotRect()</tt> to a <tt>shotRegion()</tt> that returns a <a href="qregion.html">QRegion</a> so you can have really accurate collision detection.</p>
<p>Make a moving target.</p>
<p>Make sure that the target is always created entirely on-screen.</p>
<p>Make sure that the widget cannot be resized so that the target isn't visible. [Hint: <a href="qwidget.html#minimumSize-prop">QWidget::setMinimumSize</a>() is your friend.]</p>
<p>Not easy; make it possible to have several shots in the air at the same time. [Hint: Make a <tt>Shot</tt> class.]</p>
<p>
[Previous: <a href="tutorials-tutorial-t11.html">Chapter 11</a>]
[<a href="tutorials-tutorial.html">Qt Tutorial</a>]
[Next: <a href="tutorials-tutorial-t13.html">Chapter 13</a>]
</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%" align="left">Copyright &copy; 2008 Nokia</td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.4.3</div></td>
</tr></table></div></address></body>
</html>
