Files
AutoControlSystem-git/toggleswitch.py
2024-10-30 23:19:05 +08:00

79 lines
2.5 KiB
Python

from PySide6.QtWidgets import QApplication, QWidget, QLabel
from PySide6.QtCore import QPropertyAnimation, QRect, QSize
class ToggleSwitch(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedSize(QSize(60, 30)) # 设置开关整体大小
# 背景标签(用于颜色变化)
self.background = QLabel(self)
self.background.setFixedSize(QSize(60, 30))
self.background.setStyleSheet("background-color: #ccc; border-radius: 15px;")
self.background.move(0, 0)
# 滑动圆圈
self.circle = QLabel(self)
self.circle.setFixedSize(26, 26)
self.circle.setStyleSheet("background-color: white; border-radius: 13px;")
self.circle.move(2, 2) # 初始位置
# 开关状态
self.is_on = False
# 动画效果
self.animation = QPropertyAnimation(self.circle, b"geometry")
self.animation.setDuration(200)
# 点击事件
self.mousePressEvent = self.toggle # 绑定点击事件
def toggle(self, event):
# 切换开关状态
self.is_on = not self.is_on
# 更新背景颜色和动画位置
if self.is_on:
self.background.setStyleSheet("background-color: #4CAF50; border-radius: 15px;")
self.animation.setStartValue(QRect(2, 2, 26, 26))
self.animation.setEndValue(QRect(32, 2, 26, 26))
else:
self.background.setStyleSheet("background-color: #ccc; border-radius: 15px;")
self.animation.setStartValue(QRect(32, 2, 26, 26))
self.animation.setEndValue(QRect(2, 2, 26, 26))
# 开始动画
self.animation.start()
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Toggle Switch Example")
self.setFixedSize(200, 100)
# 创建滑动开关按钮
self.toggle = ToggleSwitch(self)
self.toggle.move(70, 35) # 将开关放置在窗口中间
# 创建状态标签
self.label = QLabel("Switch is OFF", self)
self.label.move(70, 70)
# 连接滑动开关的状态切换
self.toggle.animation.finished.connect(self.update_label)
def update_label(self):
# 更新标签显示的开关状态
if self.toggle.is_on:
self.label.setText("Switch is ON")
else:
self.label.setText("Switch is OFF")
app = QApplication([])
window = MainWindow()
window.show()
app.exec()