入坑pyqt也有半年了,由於人們對事物的審美,靜態界面已經不能滿足用戶,而動畫卻給人眼前一亮,so,今天來學習pyqt的動畫了
由於資料真的是太少,本人也是有啃外國佬的英文進行摸索學習,可能也是觸及皮毛,以前全是我的學習筆記以及分析
基礎知識就不在這里贅述了,這里直接上干貨,下面是使用QPropertyAnimation一個對label大小進行改變的動畫:
這里大致介紹一下QPropertyAnimation的方法
QPropertyAnimation methods
The following table shows a few important QPropertyAnimation methods:
| Name | Description |
|---|---|
| start() | 開始動畫 |
| stop() | 停止動畫 |
| setStartValue() | 設定動畫初始值 |
| setEndValue() | 設定動畫結束值 |
| setDuration() | 設置動畫的時間,單位ms |
| setKeyValueAt() | 創建一個關鍵幀 |
| setLoopCount() | 設置動畫重復次數 |
下面是py3代碼
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ PyQt5 Animation tutorial This program animates the size of a widget with QPropertyAnimation. Author: Seshigure 401219180@qq.com Last edited: 2018.03.02 """ from PyQt5.QtWidgets import QWidget, QApplication, QLabel, QPushButton from PyQt5.QtGui import * from PyQt5.QtCore import * class Example(QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.button = QPushButton("Start", self) self.button.clicked.connect(self.doAnim) self.button.move(30, 30) self.label = QLabel("changeSize", self) self.label.setAutoFillBackground(True) # 必寫,不然調色板不能填充背景 self.palette = QPalette() # 創建一個調色板進行背景填充方便看label大小 self.palette.setColor(self.label.backgroundRole(), QColor(255, 50, 50, 50)) self.label.setPalette(self.palette) self.label.setGeometry(150, 30, 100, 100) self.setGeometry(300, 300, 380, 300) self.setWindowTitle('Animation') self.show() def doAnim(self): self.anim = QPropertyAnimation(self.label, b"geometry") self.anim.setDuration(3000) self.anim.setStartValue(QRect(150, 30, 100, 100)) # 大小100*100 self.anim.setEndValue(QRect(150, 30, 200, 200)) # 大小200*200 self.anim.start() if __name__ == "__main__": app = QApplication([]) ex = Example() ex.show() app.exec_()
界面預覽圖如下:

備注:
1、這里使用了一個調色板對label背景進行填充,方便觀察
self.label.setAutoFillBackground(True) # 必寫,不然調色板不能填充背景
self.palette = QPalette()
self.palette.setColor(self.label.backgroundRole(), QColor(255, 50, 50, 50))
self.label.setPalette(self.palette)
2、其中使用 self.anim = QPropertyAnimation(self.label, b"geometry")創建了一個動畫,()里面第一個是動畫的對象,第二個是動畫的屬性(這里的屬性為geometry)
3、通過設置初始值與結束值來改變label的大小
self.anim.setStartValue(QRect(150, 30, 100, 100)) # 大小100*100 self.anim.setEndValue(QRect(150, 30, 200, 200)) # 大小200*200
