Issue with using QPropertyAnimation with a Timer
-
Hi, I'm new to using PYQT5 and have an issue that I can’t seem to fix regardless of what I do,
I'm trying to make an app and include an animation to move a widget, the animation is tied to pressing a button.
When the button is pressed the animation plays no problem. In my app I also have a timer that counts up every second, I am doing this using a QLabel, QTimer and a setText function. The issue I am having is that every time the setText function is called, the animation reverts back to its original position which I don’t want it to do.This is the code for a basic app meant to re-create the issue, I am sure it is something obvious as I’m still learning but I would really appreciate any and all help on the matter, Thanks.
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtMultimedia import * from PyQt5.QtCore import * import sys class App(QWidget): def __init__(self): super().__init__() self.var = 1 self.setFixedSize(600, 400) self.layout = QVBoxLayout() self.layout.setAlignment(Qt.AlignCenter) self.setLayout(self.layout) self.box = QWidget() self.box.setFixedSize(50, 50) self.box.setStyleSheet('background-color: #ff0000;') self.animation = QPropertyAnimation(self.box, b'pos') self.animation.setDuration(500) self.animation.setEasingCurve(QEasingCurve.Linear) self.button = QPushButton(text="press me") self.button.clicked.connect(self.animate) self.button.setFont(QFont('Calibri', 20)) self.label = QLabel(text=str(self.var)) self.label.setFont(QFont('Calibri', 40)) self.layout.addWidget(self.box) self.layout.addWidget(self.button) self.layout.addWidget(self.label) self.timer = QTimer(self) self.timer.timeout.connect(self.updateLabel) self.timer.start(1000) def animate(self): self.animation.setStartValue(self.box.pos()) self.animation.setEndValue(QPoint(self.box.x()+100, self.box.y())) self.animation.start() def updateLabel(self): self.var += 1 self.label.setText(str(self.var)) if __name__ == '__main__': app = QApplication(sys.argv) window = App() window.show() sys.exit(app.exec_())
-
Hi and welcome to devnet,
If you want your
box
to move freely around, you have to take it out of the layout and manually place it where you want it.