代码改变世界

pyqt5 动画学习(一) 改变控件大小

2018-03-09 13:47  yongchin  阅读(8729)  评论(0编辑  收藏  举报

入坑pyqt也有半年了,由于人们对事物的审美,静态界面已经不能满足用户,而动画却给人眼前一亮,so,今天来学习pyqt的动画了

由于资料真的是太少,本人也是有啃外国佬的英文进行摸索学习,可能也是触及皮毛,以前全是我的学习笔记以及分析

基础知识就不在这里赘述了,这里直接上干货,下面是使用QPropertyAnimation一个对label大小进行改变的动画:

 

这里大致介绍一下QPropertyAnimation的方法 

 

 

QPropertyAnimation methods

 

The following table shows a few important QPropertyAnimation methods:

NameDescription
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