python - pyqt 动画导致对象部分消失
问题描述
我正在用球在 pyqt 中创建动画。但是当我增加动画的速度时,球会部分消失。我现在能做什么?请帮忙!
我的代码:
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap, QPainterPath
from PyQt5.QtCore import QPointF, QPropertyAnimation, pyqtProperty
import sys
class Ball(QLabel):
def __init__(self, parent):
super().__init__(parent)
pix = QPixmap("ball.png")
self.h = pix.height()
self.w = pix.width()
self.setPixmap(pix)
def _set_pos(self, pos):
self.move(pos.x() - self.w / 2, pos.y() - self.h / 2)
pos = pyqtProperty(QPointF, fset=_set_pos)
class Example(QWidget):
def __init__(self):
super().__init__()
self.ball = Ball(self)
self.path = QPainterPath()
self.path.moveTo(400, 30)
self.path.lineTo(900, 30)
self.setWindowTitle("ball animation")
self.setGeometry(300, 300, 1000, 300)
self.anim()
def anim(self):
self.anima = QPropertyAnimation(self.ball, b"pos")
self.anima.setDuration(3000)
self.anima.setStartValue(QPointF(30, 30))
self.anima.setEndValue(QPointF(900, 30))
self.anima.finished.connect(self.anim)
self.anima.start()
app = QApplication(sys.argv)
mw = Example()
mw.show()
sys.exit(app.exec())
当我运行这个时,我得到了这样的东西:
解决方案
改变一点点大小 QLabel 宽度
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap, QPainterPath
from PyQt5.QtCore import QPointF, QPropertyAnimation, pyqtProperty
class Ball(QLabel):
def __init__(self, parent):
super().__init__(parent)
pix = QPixmap("ball.png")
self.h = pix.height()
self.w = pix.width()
self.resize(self.w+5, self.h) # <---------------
# or
# self.setContentsMargins(0, 0, 5, 0) # <---------------
self.setPixmap(pix)
def _set_pos(self, pos):
self.move(pos.x() - self.w / 2, pos.y() - self.h / 2)
pos = pyqtProperty(QPointF, fset=_set_pos)
class Example(QWidget):
def __init__(self):
super().__init__()
self.ball = Ball(self)
self.path = QPainterPath()
self.path.moveTo(400, 30)
self.path.lineTo(900, 30)
self.setWindowTitle("ball animation")
self.setGeometry(300, 300, 1000, 300)
self.anim()
def anim(self):
self.anima = QPropertyAnimation(self.ball, b"pos")
self.anima.setDuration(3000)
self.anima.setStartValue(QPointF(30, 30))
self.anima.setEndValue(QPointF(900, 30))
self.anima.finished.connect(self.anim)
self.anima.start()
app = QApplication(sys.argv)
mw = Example()
mw.show()
sys.exit(app.exec())
球.png
推荐阅读
- c - 如何分配结构数组
- user-interface - 是否有基于 DPI 的工具栏图标尺寸标准?
- python - 提交后将表单重定向到主页 - Django
- python-3.x - python virtualenv导入失败
- pytorch - 自注意力术语中的温度是多少?
- uwp - 使用在 Windows Template Studio 中创建的 UWP 到 Uno 平台
- sql-server - SQL 函数 - 当子查询跟随 =、!=、<、<=、>、>= 或当子查询用作表达式时,这是不允许的
- android - 如何在 Jetpack Compose 中使用小部件?
- javascript - 如何屏蔽和取消屏蔽 HTML 标头文本
- twig - 在“for”上使用“if”条件