【问题标题】:Change The background color of a QPushButton progressively and in a time duration?在一段时间内逐步更改 QPushButton 的背景颜色?
【发布时间】:2016-04-02 11:44:10
【问题描述】:

我已经厌倦了搜索!

我从 QPushbutton 继承了一个 Button 并将我的 QSS 设置为它。样式是需要的。

我想要的只是当按钮悬停时(enterevent 发生)按钮的颜色在特定时间(例如 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;")

【问题讨论】:

    标签: qt pyqt pyqt5 qpushbutton


    【解决方案1】:

    其中一个解决方案是 - 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 - 你的变量anim 不是全局变量,只要方法执行就被销毁。我在anim=QPropertyAnimation(self, "color") 之前添加了行global anim 并且动画正确
    • @IMAN4K 多亏了你,我终于在我的 ubuntu 机器上设置了 pyqt。现在我也可以开始学习 python,而不仅仅是 c++ :D
    • 听起来不错 ;)
    猜你喜欢
    • 2016-06-25
    • 2014-01-07
    • 2014-08-30
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 2012-07-26
    相关资源
    最近更新 更多