pyside6 写个switch开关

pyside6 写个switch开关_第1张图片


from PySide6 import QtWidgets,QtCore,QtGui
from PySide6.QtCore import Qt, QPoint,QPropertyAnimation
from PySide6.QtGui import QPainter, QFont


class SwitchButton(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        # self.resize(300,80)

        self.isoff = True

        self.offBgBrush = Qt.black
        self.onBgBrush = Qt.blue

        #定义滑块颜色
        self.offIndicatorBrush = Qt.red
        self.onIndicatorBrush = Qt.green

        self.offText = 'off'
        self.onText = 'on'


        self.animation = QPropertyAnimation()
        self.animation.setTargetObject(self)
        self.animation.setDuration(300)
        self.currentX = int(self.height()/2)

        #slots
        self.animation.valueChanged.connect(self.fun)

    def fun(self,val):
        self.currentX = str(val)

        self.update()


    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing,True)
        painter.setPen(Qt.NoPen)
        painter.setBrush(self.offBgBrush if self.isoff else self.onBgBrush)
        painter.drawRoundedRect(self.rect(),self.height()/2,self.height()/2)

        #绘制滑块颜色
        painter.setBrush(self.offIndicatorBrush if self.isoff else self.onIndicatorBrush)
        #定义滑块圆心位置
        if self.isoff:
            center = QPoint(self.height()/2,self.height()/2)
        else:
            center = QPoint(self.width()-self.height()/2,self.height()/2)
        painter.drawEllipse(center,self.height()/2-10,self.height()/2-10)




        painter.setPen(Qt.white)
        painter.setFont(QFont("微软雅黑",10))
        painter.drawText(self.rect(),Qt.AlignmentFlag.AlignCenter,self.offText if self.isoff else self.onText)

    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self.isoff = not self.isoff
            self.update()

    def resizeEvent(self, event):
        self.animation.setStartValue(self.height()/2)
        self.animation.setEndValue(self.width()-self.height()/2)

class Ui(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.resize(1100,900)

        self.btn = SwitchButton()
        self.btn.setParent(self)
        self.btn.resize(100,40)
        self.btn.move(20,20)

        self.btn2 = SwitchButton()
        self.btn2.setParent(self)
        self.btn2.resize(100, 40)
        self.btn2.move(220, 20)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)

    win = Ui()
    win.show()

    sys.exit(app.exec())

你可能感兴趣的:(pyqt)