1、示例
2、功能实现
# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import QPushButton, QApplication, QWidget, QMainWindow
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import cgitb
import sys
cgitb.enable(format='text') # 解决pyqt5异常只要进入事件循环,程序就崩溃,而没有任何提示
class Rotation(QObject):
def __init__(self):
super().__init__()
pixmap = QPixmap("qq.png")
scaledPixmap = pixmap.scaled(40, 40) # 动画大小
self.animation()
self.pixmap_item = QGraphicsPixmapItem(scaledPixmap)
self.pixmap_item.setTransformOriginPoint(20, 20) # 设置中心为旋转
def _set_rotation(self, degree):
self.pixmap_item.setRotation(degree) # 自身改变旋转度数
def animation(self):
self.anim = QPropertyAnimation(self, b'rotation') # 动画类型
self.anim.setDuration(1000)
self.anim.setStartValue(0) # 初始角度
self.anim.setEndValue(360)
self.anim.setLoopCount(-1) # 设置循环旋转
rotation = pyqtProperty(int, fset=_set_rotation) # 属性动画改变自身数值
class WinForm(QGraphicsView,QMainWindow):
def __init__(self, parent=None):
super(WinForm, self).__init__(parent)
self.setWindowTitle('rotation animation') # 设置窗口标题
self.setWindowTitle("rotation animation")
self.setGeometry(100, 100, 400, 400) # 窗口整体窗口位置大小
quit = QPushButton('click', self) # button 对象
quit.setGeometry(10, 10, 60, 35) # 设置按钮的位置 和 大小
quit.setStyleSheet("background-color: red") # 设置按钮的风格和颜色
quit.clicked.connect(self.clickbutton) # 点击按钮之后关闭窗口
self.rota = Rotation()
self.scene = QGraphicsScene(self)
self.scene.setSceneRect(0, 0, 40, 40) # 动画 位置 这个需计算
self.scene.addItem(self.rota.pixmap_item)
self.setScene(self.scene)
self.stop = False
def clickbutton(self):
print("click")
if not self.stop:
self.rota.anim.start()
else:
self.rota.anim.stop()
self.stop = ~self.stop
# self.rota.anim.stop() #动画停止
# self.scene.deleteLater() #删除加载的动画
if __name__ == "__main__":
app = QApplication(sys.argv)
win = WinForm() # 实体化 类
win.show()
sys.exit(app.exec_())
备注:
让我们创建好QGraphicsView后,需要再创建一个QGraphicsScene场景,然后通过self.scene.addItem(self.ball.pixmap_item)把对象添加到场景里面,最后再通过self.setScene(self.scene)把场景添加进界面即可
文章参考:
pyqt5 动画学习(四) 旋转动画,使用QGraphicsView让自己的控件旋转起来
Qt 常见的 QGraphicsItem