简体   繁体   English

QPainter不会改变颜色

[英]QPainter doesn't change color

I'm learning Qt . 我正在学习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." 我未能实现Qt教程第11章的练习,该章指出“空中射击时改变加农炮的颜色”。 I chose to implement the change in paintCannon function (below). 我选择实现paintCannon函数的更改(如下)。 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. 由于我最初怀疑Qpaintersaverestore可能做错了什么,因此我对它们进行了评论,最终没有重新绘画。

Thanks. 谢谢。

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. 移动镜头时,将使用指定的区域调用update() 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. 如果您从对update()的调用中删除了该区域,则会重新绘制整个小部件,并且颜色更改将正确进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM