[SOLVED] QPainter doesn't change color

Issue

I’m learning Qt. I’m failing to realize the exercise of chapter 11 of Qt tutorial, which states "Change the color of the cannon when a shot is in the air." I chose to implement the change in paintCannon function (below). What’s wrong with my code below?

void CannonField::paintCannon(QPainter &painter)
{
    painter.setPen(Qt::NoPen);
    if (autoShootTimer->isActive()){

        std::cout << "in paintCannon yellow; "  << std::endl; 
        // This gets called everytime `paintEvent` occurs. 
        // Please see the code in the web page (http://doc.trolltech.com/4.3/tutorial-t11-cannonfield-cpp.html) for this part.

        painter.setBrush(Qt::yellow);
    }else{
        std::cout << "in paintCannon blue; "  << std::endl;
        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();
}

Since I first suspected Qpainter‘s save and restore might have been doing something wrong, I commented them out which ended up re-painting nothing.

Thanks.

Solution

The problem you are having is in this routine:

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);
}

When the shot is moved, update() is being called with a region specified. This results in only the shot rectangle being repainted. If you remove the region from the call to update(), the entire widget is repainted and your color change will work correctly.

Answered By – Arnold Spence

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *