qtbrightnessqpushbuttonqicon

Changing fluently brightness of QPushButton icon


I found a function to make QImage brighter and used in my Qt application. I want to show simple "animation" of making button step by step brighter and than again step by step back to initial state after user click it.

Here my code:

void Widget::on_stopButton_clicked(){

    player.stop();

    for(int i = 0; i <= 50; ++i){

        QImage* image = new QImage(":/Graphics/Graphics/StopButton.png");
        changeBrightness(*image, i);
        QPixmap* pixmap = new QPixmap(QPixmap::fromImage(*image));
        ui->stopButton->setIcon(QIcon(*pixmap));
        QThread::msleep(50);

    } 

}

It doesn't work as I expected... I see only the final effect, so the last call: changeBrightness(*image, 50);

It seems that user can see changes on form only after function ends, is it right? Is there other way to make such "animation"?


Solution

  • You do not give Qt any time to redraw the widget after you update the button's image, because you are stuck in the loop. Only after you finished updating the image, Qt will be able to redraw your widget, which is why you only see the final result.

    Look into QTimer. You can set its timeout to 50 milliseconds via QTimer::setInterval. Then connect a slot that changes the color of the button's image to QTimer::timeout. This slot will be much like your code, but without the loop. E.g. each call of the slot is a single iteration of your loop. Finally, to start or stop the animation, you call QTimer::start or QTimer::stop.