95 lines
3.1 KiB
Python
95 lines
3.1 KiB
Python
from PySide6.QtCore import Qt, QSize, QPropertyAnimation, Signal
|
|
from PySide6.QtGui import QColor, QPainter, QBrush
|
|
from PySide6.QtWidgets import QWidget, QMainWindow, QLabel, QVBoxLayout, QApplication
|
|
|
|
|
|
class WidgetSwitchButton(QWidget):
|
|
signal_clicked = Signal(bool)
|
|
def __init__(self, parent=None, width=40, height=14):
|
|
super(WidgetSwitchButton, self).__init__(parent)
|
|
|
|
self.w = width
|
|
self.h = height
|
|
|
|
self.slider_diameter = self.h - 4
|
|
self.setFixedSize(self.w, self.h) # 设置控件大小
|
|
self.is_checked = False # 开关状态,默认关闭
|
|
|
|
# 开启动画
|
|
self.animation = QPropertyAnimation(self, b"pos")
|
|
self.animation.setDuration(200)
|
|
|
|
self.setCursor(Qt.CursorShape.PointingHandCursor)
|
|
self.setStyleSheet("background-color: transparent;")
|
|
|
|
def sizeHint(self):
|
|
return QSize(self.w, self.h)
|
|
|
|
def mousePressEvent(self, event):
|
|
# 点击切换状态
|
|
self.is_checked = not self.is_checked
|
|
self.update() # 更新UI
|
|
self.signal_clicked.emit(self.is_checked)
|
|
|
|
def paintEvent(self, event):
|
|
# 定义背景颜色和滑块颜色
|
|
background_color = QColor(255, 195, 0 ) if self.is_checked else QColor(150, 150, 150)
|
|
slider_color = QColor(255, 255, 255)
|
|
|
|
# 创建画笔
|
|
painter = QPainter(self)
|
|
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
|
|
|
# 绘制背景
|
|
painter.setBrush(QBrush(background_color))
|
|
painter.setPen(Qt.PenStyle.NoPen)
|
|
painter.drawRoundedRect(0, 0, self.width(), self.height(), int(self.h/2), int(self.h/2))
|
|
|
|
# 绘制滑块
|
|
slider_x = (self.width() - (self.slider_diameter+2)) if self.is_checked else 2
|
|
painter.setBrush(QBrush(slider_color))
|
|
painter.drawEllipse(slider_x, 2, self.slider_diameter, self.slider_diameter)
|
|
|
|
def setChecked(self, checked):
|
|
# 设置开关状态
|
|
self.is_checked = checked
|
|
self.update()
|
|
|
|
def isChecked(self):
|
|
return self.is_checked
|
|
|
|
|
|
if __name__ == '__main__':
|
|
class MainWindow(QMainWindow):
|
|
def __init__(self):
|
|
super().__init__()
|
|
|
|
self.setWindowTitle("Switch Button Example")
|
|
self.setGeometry(100, 100, 200, 100)
|
|
|
|
# 创建 SwitchButton 和状态标签
|
|
self.switch = WidgetSwitchButton(width=30, height=10)
|
|
self.status_label = QLabel("Off")
|
|
|
|
# 绑定开关事件
|
|
self.switch.clicked.connect(self.on_switch_toggled)
|
|
|
|
# 布局
|
|
layout = QVBoxLayout()
|
|
layout.addWidget(self.switch)
|
|
layout.addWidget(self.status_label)
|
|
|
|
central_widget = QWidget()
|
|
central_widget.setLayout(layout)
|
|
self.setCentralWidget(central_widget)
|
|
|
|
def on_switch_toggled(self, checked):
|
|
self.status_label.setText("On" if checked else "Off")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print(QApplication.instance())
|
|
app = QApplication([])
|
|
window = MainWindow()
|
|
window.show()
|
|
app.exec() |