源码可以在Github上下载,后续会不断更新,并且提供C++版本组件,欢迎各位关注。
本文使用了遵循GPLv3许可证的开源代码-Qt-RoastedDuck-Widgets,以下代码遵循GPLv3许可证。
class SwitchButtonBase(QToolButton):
def __init__(self, parent: QWidget = None):
super().__init__(parent)
self.setCheckable(True)
self._indicatorX = 0
self.animaInit()
def animaInit(self):
self.slideAni = QPropertyAnimation(self, b'indicatorX')
self.slideAni.setDuration(200)
def animaParamsInit(self):
self.start = self.height() // 2
self.end = self.width() - 2 - self.start
self._indicatorX = self.start
def setParams(self):
pass
def toggle(self):
self.setChecked(not self.isChecked())
def mouseReleaseEvent(self, event) -> None:
super().mouseReleaseEvent(event)
if self.isChecked():
self.slideAni.setEndValue(self.end)
else:
self.slideAni.setEndValue(self.start)
self.slideAni.start()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHints(QPainter.Antialiasing)
self.paintBackground(painter)
self.paintIndicator(painter)
def paintBackground(self, painter: QPainter):
pass
def paintIndicator(self, painter: QPainter):
pass
@Property(float)
def indicatorX(self):
return self._indicatorX
@indicatorX.setter
def indicatorX(self, x):
self._indicatorX = x
self.update()
def showEvent(self, event):
super().showEvent(event)
self.animaParamsInit()