|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +""" |
| 5 | +Created on 2019年5月8日 |
| 6 | +@author: Irony |
| 7 | +@site: https://pyqt5.com https://github.com/892768447 |
| 8 | +@email: 892768447@qq.com |
| 9 | +@file: ShakeWindow |
| 10 | +@description: 抖动动画 |
| 11 | +""" |
| 12 | +from PyQt5.QtCore import QPropertyAnimation, QPoint |
| 13 | +from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton |
| 14 | + |
| 15 | + |
| 16 | +__Author__ = 'Irony' |
| 17 | +__Copyright__ = 'Copyright (c) 2019 Irony' |
| 18 | +__Version__ = 1.0 |
| 19 | + |
| 20 | + |
| 21 | +class Window(QWidget): |
| 22 | + |
| 23 | + def __init__(self, *args, **kwargs): |
| 24 | + super(Window, self).__init__(*args, **kwargs) |
| 25 | + self.resize(400, 400) |
| 26 | + layout = QVBoxLayout(self) |
| 27 | + layout.addWidget(QPushButton('抖动', self, clicked=self.doShake)) |
| 28 | + |
| 29 | + def doShake(self): |
| 30 | + self.doShakeWindow(self) |
| 31 | + |
| 32 | + # 下面这个方法可以做成这样的封装给任何控件 |
| 33 | + def doShakeWindow(self, target): |
| 34 | + """窗口抖动动画 |
| 35 | + :param target: 目标控件 |
| 36 | + """ |
| 37 | + if hasattr(target, '_shake_animation'): |
| 38 | + # 如果已经有该对象则跳过 |
| 39 | + return |
| 40 | + |
| 41 | + animation = QPropertyAnimation(target, b'pos', target) |
| 42 | + target._shake_animation = animation |
| 43 | + animation.finished.connect(lambda: delattr(target, '_shake_animation')) |
| 44 | + |
| 45 | + pos = target.pos() |
| 46 | + x, y = pos.x(), pos.y() |
| 47 | + |
| 48 | + animation.setDuration(200) |
| 49 | + animation.setLoopCount(2) |
| 50 | + animation.setKeyValueAt(0, QPoint(x, y)) |
| 51 | + animation.setKeyValueAt(0.09, QPoint(x + 2, y - 2)) |
| 52 | + animation.setKeyValueAt(0.18, QPoint(x + 4, y - 4)) |
| 53 | + animation.setKeyValueAt(0.27, QPoint(x + 2, y - 6)) |
| 54 | + animation.setKeyValueAt(0.36, QPoint(x + 0, y - 8)) |
| 55 | + animation.setKeyValueAt(0.45, QPoint(x - 2, y - 10)) |
| 56 | + animation.setKeyValueAt(0.54, QPoint(x - 4, y - 8)) |
| 57 | + animation.setKeyValueAt(0.63, QPoint(x - 6, y - 6)) |
| 58 | + animation.setKeyValueAt(0.72, QPoint(x - 8, y - 4)) |
| 59 | + animation.setKeyValueAt(0.81, QPoint(x - 6, y - 2)) |
| 60 | + animation.setKeyValueAt(0.90, QPoint(x - 4, y - 0)) |
| 61 | + animation.setKeyValueAt(0.99, QPoint(x - 2, y + 2)) |
| 62 | + animation.setEndValue(QPoint(x, y)) |
| 63 | + |
| 64 | + animation.start(animation.DeleteWhenStopped) |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == '__main__': |
| 68 | + import sys |
| 69 | + from PyQt5.QtWidgets import QApplication |
| 70 | + app = QApplication(sys.argv) |
| 71 | + w = Window() |
| 72 | + w.show() |
| 73 | + sys.exit(app.exec_()) |
0 commit comments