点击按钮实现值交换
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QLabel
from PyQt5.QtCore import QPropertyAnimation, QPoint, QTimer
import time
class AnimatedTextLabel(QLabel):
def __init__(self, text, x_y, parent=None):
super().__init__(text, parent)
self.x_y = x_y
self._animation = QPropertyAnimation(self, b"pos")
self._animation.setDuration(500) # Animation duration in milliseconds
def setEndPos(self, pos):
print("setEndPos kais")
start_pos = self.pos()
self._animation.setStartValue(start_pos)
self._animation.setEndValue(pos)
self._animation.start()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Animate Text Move")
self.timer = QTimer(self)
self.timer.setSingleShot(True) # Timer only triggers once
self.timer.timeout.connect(self.process_click)
# Create buttons
self.button1 = QPushButton("Button 1", self)
# self.button2 = QPushButton("Button 2", self)
self.label1 = AnimatedTextLabel("Text 1", (60, 60, 100, 50), self)
self.label2 = AnimatedTextLabel("Text 2", (210, 60, 100, 50), self)
self.label1_pos=(60, 60, 100, 50)
self.label1.setGeometry(*self.label1.x_y) # Position within button1
self.label2.setGeometry(*self.label2.x_y) # Position within button2
self.button1.setGeometry(50, 50, 200, 100)
self.button1.clicked.connect(self.swap_texts)
layout = QVBoxLayout()
layout.addWidget(self.button1)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
def swap_texts(self):
print("开始")
pos1 = QPoint(self.label1.x_y[0], self.label1.x_y[1])
pos2 = QPoint(self.label2.x_y[0], self.label2.x_y[1])
self.label1.setEndPos(pos2)
self.label2.setEndPos(pos1)
self.label1.x_y, self.label2.x_y = self.label2.x_y, self.label1.x_y
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())