Qt 是否在一段时间内逐步更改QPushButton的背景色?
我厌倦了寻找 我从QPushbutton子类化了一个按钮,并将我的QSS设置为它 我想要的是当按钮悬停(enterevent-occure)时,按钮的颜色会在特定时间(例如0.2秒)内发生变化,而不是立即发生(柔和的颜色变化) 我该怎么办 *******用PyQt4回答*********Qt 是否在一段时间内逐步更改QPushButton的背景色?,qt,pyqt,pyqt5,qpushbutton,Qt,Pyqt,Pyqt5,Qpushbutton,我厌倦了寻找 我从QPushbutton子类化了一个按钮,并将我的QSS设置为它 我想要的是当按钮悬停(enterevent-occure)时,按钮的颜色会在特定时间(例如0.2秒)内发生变化,而不是立即发生(柔和的颜色变化) 我该怎么办 *******用PyQt4回答********* class MyButton(QPushButton): def __init__(self): super(MyButton, self).__init__() sel
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;")
解决方案之一是-
QPropertyImation
class。它不支持开箱即用的颜色更改,但由于您已经对按钮进行了子类化,下面是一个示例代码
首先-您需要在类中定义新属性-就在Q_对象宏之后。以及此属性的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确保您没有内存泄漏谢谢您的回复。我按您所说的做了,但似乎没有什么不同。如果您验证我的编辑,我将不胜感激。谢谢again@IMAN4K-您的变量
anim
不是全局变量,并且在方法执行后立即销毁。我在anim=QPropertyAnimation(self,“color”)
之前添加了行global anim
,并对其设置了动画correctly@IMAN4K多亏了你,我终于在我的ubuntu机器上安装了pyqt。现在我也可以开始学习Python,而不是C++:听起来很棒!