IMA*_*N4K 3 qt pyqt qpushbutton pyqt5
我厌倦了搜索!
我从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;")
Run Code Online (Sandbox Code Playgroud)
其中一个解决方案是 - 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
}
};
Run Code Online (Sandbox Code Playgroud)
然后在你处理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();
Run Code Online (Sandbox Code Playgroud)
虽然你可能想确保不启动新的动画,除非这个完成,并确保你没有一次又一次地调用新的内存泄漏
| 归档时间: |
|
| 查看次数: |
861 次 |
| 最近记录: |