我如何使旋转动画化?在我的例子中,我有一个角度,这是一个QVariant类型。通过阅读文档,我看到要用QVariantAnimation动画一些东西,我的变量必须是QVariant类型,在本例中,浮动就是。但我的代码没有运行。我不知道在Qt的最后一个版本中,float是否是QVariant,而且它不是更多。
这是我的密码,有人能帮我吗?提前感谢!
from PyQt5 import QtWidgets, QtCore, QtGui
import sys
pen = QtGui.QPen(QtGui.QColor(0, 24, 128, 200), 10, style=QtCore.Qt.SolidLine, cap=QtCore.Qt.SquareCap)
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window, self).__init__()
central_widget = QtWidgets.QWidget()
self.scene = QtWidgets.QGraphicsScene(self)
self.view = QtWidgets.QGraphicsView(self.scene)
self.view.setSceneRect(self.view.mapToScene(self.view.viewport().rect()).boundingRect())
self.btn = QtWidgets.QPushButton('Rotate')
self.btn.clicked.connect(self.animateRotation)
hbox = QtWidgets.QHBoxLayout(central_widget)
hbox.addWidget(self.view)
hbox.addWidget(self.btn)
self.scene.addEllipse(QtCore.QRectF(0, 0, 100, 250), pen=pen)
self.view.setBackgroundBrush(QtGui.QBrush(QtCore.Qt.CrossPattern))
self.setCentralWidget(central_widget)
print(self.scene.items()[0])
def rot(self, angle: QtCore.QVariant) -> None:
self.view.rotate(self.scene.items()[0].rotation()-angle)
self.scene.items()[0].setRotation(angle)
@QtCore.pyqtSlot()
def animateRotation(self):
animation = QtCore.QVariantAnimation()
animation.setStartValue(QtCore.QVariant(0))
animation.setEndValue(QtCore.QVariant(45))
animation.start(QtCore.QAbstractAnimation.DeleteWhenStopped)
animation.valueChanged.connect(self.rot)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())发布于 2020-12-24 04:23:13
问题是动画变量的生命周期,因为它是一个局部变量,只有在animateRotation完成执行时,它才会被销毁,也就是说,一旦动画开始,动画就无法工作。
解决方案是延长变量的生命周期,对于Qt,有以下选项:
通过将类的变量属性更改为self.animation.,
animation = QtCore.QVariantAnimation(self).
QVariantAnimation,例如self变量:selfhttps://stackoverflow.com/questions/65433827
复制相似问题