如何逐步改变QPushButton的背景颜色并设置变化时间?

3

我已经厌倦了搜索!

我从QPushbutton子类化了一个按钮,并将我的QSS设置为它。样式是期望的。

我想要的只是当鼠标悬停在按钮上时(触发enter事件),按钮的颜色会在特定时间内(例如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个回答

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而出现内存泄漏。


谢谢您的回复。我按照您说的做了一切,但似乎没有什么不同。如果您能验证我的编辑,我将不胜感激。再次感谢。 - IMAN4K
@IMAN4K - 你的变量 anim 不是全局的,当方法执行完毕时就会被销毁。我在 anim=QPropertyAnimation(self, "color") 前添加了一行 global anim,然后它就正确地进行了动画处理。 - Shf
@IMAN4K,感谢您,我终于在我的Ubuntu机器上安装了PyQt。现在我可以开始学习Python,而不仅仅是C++ :D - Shf
听起来不错 ;) - IMAN4K

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接