PDA

View Full Version : Qt Tutorial #1 Add-on Part II



ShaChris23
24th April 2007, 23:56
Hi guys,

For this tutorial here,

http://doc.trolltech.com/4.2/tutorial-t11.html

At the end of the tutorial, there's an exercise that says:

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

How do we achieve that? I tried it for like 2-3 hours, but still couldnt get it to work.

marcel
25th April 2007, 01:40
In the following function you have to see if the cannon is in the air, meaning autoShootTimer->isActive().


void CannonField::paintCannon(QPainter &painter)
{
painter.setPen(Qt::NoPen);
if( autoShootTimer->isActive() //bullet is in the air
painter.setBrush( Qt::red );
else //bullet is not in the air
painter.setBrush(Qt::blue);
painter.save();
painter.translate(0, height());
painter.drawPie(QRect(-35, -35, 70, 70), 0, 90 * 16);
painter.rotate(-currentAngle);
painter.drawRect(barrelRect);
painter.restore();
}


Regards

ShaChris23
25th April 2007, 02:18
Hi,

Has anybody tried this modification? I'm not sure if I did something, but this is what I have tried before and my cannon's color never changed each time I pressed the shoot button.

Here's the simple code modification that didnt work for me:



void CannonField::paintCannon( QPainter& painter )
{
painter.setPen( Qt::NoPen );

if( autoShootTimer->isActive() )//bullet is in the air
{
painter.setBrush( Qt::red );
}
else //bullet is not in the air
{
painter.setBrush(Qt::blue);
}

painter.save();
painter.translate(0, height());
painter.drawPie(QRect(-35, -35, 70, 70), 0, 90 * 16 );
painter.rotate(-currentAngle);
painter.drawRect(barrelRect);
painter.restore();
}

marcel
25th April 2007, 06:17
Actually the cannon rect wasn't updated at repaint. Try this



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

QRect shotR = shotRect();
QRect cannonR = cannonRect();

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


Regards

ShaChris23
25th April 2007, 19:40
Hi Marcel,

Thank you. Now that I added that code, the cannon changes from blue to red. However, it stays red even when the shot is off screen. Is there a remedy to re-paint it blue?

marcel
25th April 2007, 20:00
Actually, it is, if you modify the code above a bit:



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

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


This way the cannon will be updated even after the timer is stopped ( the bullet is off-screen ). If the timer is stopped, then the cannon will be painted with the original color.

Regards.