Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change The background color of a QPushButton progressively and in a time duration?

I am tired of searching !

i subclassed a Button from QPushbutton and set my QSS to it.the style is desired.

all i want is when the button is hover (enterevent happen) the button's color change over a specific time (for example 0.2 sec) not immediately (a soft color changing)

what should i do ?

*******Answer in PyQt4*********

class MyButton(QPushButton):
    def __init__(self):
        super(MyButton, self).__init__()
        self.setMinimumSize(80,50)
        self.setText('QPushButton')

    def getColor(self):
        return Qt.black

    def setColor(self, color):
        self.setStyleSheet("background-color: rgb({0}, {1}, {2});border:none;".format(color.red(), color.green(), color.blue()))

    color=QtCore.pyqtProperty(QColor, getColor, setColor)

    def enterEvent(self, event):
        global anim
        anim=QPropertyAnimation(self, "color")
        anim.setDuration(200)
        anim.setStartValue(QColor(216, 140, 230))
        anim.setEndValue(QColor(230, 230, 230))
        anim.start()

    def leaveEvent(self, event):
        self.setStyleSheet("background:none;")
like image 594
IMAN4K Avatar asked Nov 17 '25 08:11

IMAN4K


1 Answers

One of the solutions is - QPropertyAnimation class. It does not support color change out of box, but since you have subclassed button already anyway - here is a sample code.

First - you would need to define new property in your class - right after Q_OBJECT macro. And getter and setter methods for this property, example below:

class AnimatedButton : public QPushButton
{

  Q_OBJECT
  Q_PROPERTY(QColor color READ color WRITE setColor)

public:
  AnimatedButton (QWidget *parent = 0)
  {
  }
  void setColor (QColor color){
    setStyleSheet(QString("background-color: rgb(%1, %2, %3);").arg(color.red()).arg(color.green()).arg(color.blue()));
  }
  QColor color(){
    return Qt::black; // getter is not really needed for now
  }
};

and then in your event handler, where you process enterEvent, you should do something like this -

// since it will be in event of button itself, change myButton to 'this'
QPropertyAnimation *animation = new QPropertyAnimation(myButton, "color");
animation->setDuration(200); // duration in ms
animation->setStartValue(QColor(0, 0, 0));
animation->setEndValue(QColor(240, 240, 240));
animation->start();

though you would probably want to make sure to not start new animation unless this one is finished, and make sure that you don't have memory leak by calling new again and again

like image 135
Shf Avatar answered Nov 19 '25 08:11

Shf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!