QPushButton的背景颜色是否会逐渐变化?

时间:2015-12-28 15:58:15

标签: qt pyqt pyqt5 qpushbutton

我厌倦了搜索!

我从QPushbutton继承了一个Button并将我的QSS设置为它。需要这种风格。

所有我想要的是当按钮悬停(事后发生)按钮的颜色在特定时间(例如0.2秒)内的颜色变化不是立即(软颜色变化)

我该怎么办?

*******回答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;")

1 个答案:

答案 0 :(得分:5)

其中一个解决方案是 - QPropertyAnimation类。它不支持开箱即用的颜色更改,但由于你已经有了子类按钮 - 这里是一个示例代码。

首先 - 你需要在你的类中定义新属性 - 就在Q_OBJECT宏之后。以及此属性的getter和setter方法,例如:

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

然后在你处理enterEvent的事件处理程序中,你应该做这样的事情 -

// 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();

虽然您可能希望确保不启动新动画,除非这个动画完成,并确保通过一次又一次地调用new来避免内存泄漏

相关问题