Код: Выделить всё
class Switch(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedSize(50, 25)
self._checked = False
self.animation = QPropertyAnimation(self, b"pos")
self.animation.setDuration(100)
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
# Draw background
brush = QBrush(QColor("#333333") if not self._checked else QColor("#FFD700"))
painter.setBrush(brush)
painter.setPen(Qt.NoPen)
painter.drawRoundedRect(0, 0, self.width(), self.height(), 12, 12)
# Draw knob
painter.setBrush(QBrush(QColor("white")))
if self._checked:
painter.drawEllipse(25, 2, 21, 21)
else:
painter.drawEllipse(4, 2, 21, 21)
def mouseReleaseEvent(self, event):
self._checked = not self._checked
self.animate_knob() # Call the new method for animation
self.update()
def animate_knob(self):
# Set the start and end positions based on the current state
if self._checked:
self.animation.setStartValue(self.pos())
self.animation.setEndValue(self.pos() + QPoint(3, 0)) # Move right by 3 pixels
else:
self.animation.setStartValue(self.pos())
self.animation.setEndValue(self.pos() - QPoint(3, 0)) # Move left by 3 pixels
self.animation.start()
def isChecked(self):
return 1 if self._checked else 0
def setChecked(self, checked):
self._checked = checked
self.animate_knob() # Call the new method for animation
self.update()
Код: Выделить всё
for label_text in ["Power Mode", "Relay", "Pump", "Output Valve"]:
layout = QHBoxLayout()
label = QLabel(label_text)
switch = Switch()
layout.addWidget(label)
layout.addWidget(switch)
layout.addStretch()
mode_layouts.append(layout)
self.switches[label_text] = switch # Store the switch reference with its name
right_controls.addLayout(layout)
Подробнее здесь: https://stackoverflow.com/questions/792 ... tton-class
Мобильная версия