pyqt5 按钮效果

pyqt5实现按钮效果

1.按钮实现点击后在一定范围内左右移动

2.按钮点击后外围颜色红绿变换

3.添加锁定和解锁两个图标

import sys

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout
from PyQt5.QtCore import QPropertyAnimation, QRect, QEasingCurve


class SlidingButton(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('滑动按钮演示')
        # self.setFixedSize(300, 100)  # 固定窗口大小

        # 创建容器用于放置滑动按钮
        self.container = QWidget(self)
        self.container.setObjectName("B1")
        self.container.setGeometry(50, 25, 104, 54)
        self.container.setStyleSheet("#B1 {background-color: #DC143C;border-radius: 25px;}")
        # 创建可滑动的按钮
        self.button = QPushButton(self.container)
        self.button.setIcon(QIcon("E:/1TUF/上鎖.png"))
        self.button.setGeometry(2, 2, 50, 50)
        self.button.setStyleSheet("""
            QPushButton {
                background-color:#FFFFFF;
                border-radius: 25px;
                border: none;
            }
            QPushButton:hover {
                background-color: #64b5f6;
            }
        """)
        self.button.clicked.connect(self.slide_button)

        # 动画设置
        self.animation = QPropertyAnimation(self.button, b"geometry")
        self.animation.setDuration(100)  # 动画持续时间(毫秒)
        self.animation.setEasingCurve(QEasingCurve.Linear)  # 弹性效果
        # 状态跟踪
        self.is_left = True  # 初始状态在左侧

    def slide_button(self):
        """切换按钮位置并启动动画"""
        if self.is_left:
            self.container.setStyleSheet("#B1 {background-color: #00FA9A;border-radius: 25px;}")
            self.button.setIcon(QIcon("E:/1TUF/解鎖.png"))
            # 滑动到右侧 (150 = 容器宽度200 - 按钮宽度50)
            self.animation.setStartValue(QRect(2, 2, 50, 50))
            self.animation.setEndValue(QRect(52, 2, 50, 50))
            print(f"按钮状态: 開")
        else:
            # 滑动回左侧
            self.container.setStyleSheet("#B1 {background-color: #DC143C;border-radius: 25px;}")
            self.button.setIcon(QIcon("E:/1TUF/上鎖.png"))
            self.animation.setStartValue(QRect(52, 2, 50, 50))
            self.animation.setEndValue(QRect(2, 2, 50, 50))
            print(f"按钮状态: 関")

        self.animation.start()
        self.is_left = not self.is_left  # 切换状态



if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = SlidingButton()
    window.show()
    sys.exit(app.exec_())

实现效果如下

        pyqt5 按钮效果_第1张图片                                                pyqt5 按钮效果_第2张图片

你可能感兴趣的:(pyqt5 按钮效果)