用pyqt5实现的滑动开关(有动画效果)

本文详细介绍了如何使用Python的PyQt5库创建一个具有动画效果的开关按钮,包括初始化、设置文本、状态切换以及鼠标事件处理。
摘要由CSDN通过智能技术生成

1、效果展示

2、控件源码

import sys
from PyQt5.QtCore import Qt, QRect, QPoint, QVariantAnimation
from PyQt5.QtGui import QPainter, QColor
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout


class SwitchButton(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedSize(50, 30)
        self.checked = False
        self.setCursor(Qt.PointingHandCursor)
        self.animation = QVariantAnimation()
        self.animation.setDuration(80)  # 动画持续时间
        self.animation.setStartValue(0)
        self.animation.setEndValue(20)
        self.animation.valueChanged.connect(self.update)
        self.animation.finished.connect(self.onAnimationFinished)

    def setText(self, value):
        pass

    def isChecked(self):
        return self.checked

    def setChecked(self, check):
        self.checked = check
        self.animation.setDirection(QVariantAnimation.Forward if self.checked else QVariantAnimation.Backward)
        self.animation.start()

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(Qt.NoPen)
        if self.checked:
            painter.setBrush(QColor('#07c160'))  # 选中颜色
        else:
            painter.setBrush(QColor('#d5d5d5'))  # 未选中颜色

        # 绘制外框
        painter.drawRoundedRect(QRect(0, 0, self.width(), self.height()), 15, 15)

        # 按钮位置
        offset = self.animation.currentValue()

        # 绘制按钮
        painter.setBrush(QColor(255, 255, 255))
        painter.drawEllipse(QPoint(15 + offset, 15), 12, 12)

    def mouseReleaseEvent(self, event) -> None:
        if event.button() == Qt.LeftButton:
            self.checked = not self.checked
            self.animation.setDirection(QVariantAnimation.Forward if self.checked else QVariantAnimation.Backward)
            self.animation.start()

    def onAnimationFinished(self):
        pass


class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        layout = QHBoxLayout()
        switch = SwitchButton()
        layout.addWidget(switch)
        self.setLayout(layout)
        self.setFixedSize(400, 200)


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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值