pyqt5 switch
时间: 2023-12-12 12:35:29 浏览: 80
PyQt5
以下是使用 PyQt5 创建一个滑动开关控件的步骤和代码示例:
步骤1:安装 PyQt5
如果您尚未安装 PyQt5 库,可以使用以下命令来安装:
```shell
pip install pyqt5
```
步骤2:创建 SwitchButton 类
```python
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QPainter, QColor, QBrush
from PyQt5.QtWidgets import QWidget
class SwitchButton(QWidget):
# 定义信号
stateChanged = pyqtSignal(bool)
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedSize(50, 30)
self.checked = False
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
painter.setPen(Qt.NoPen)
if self.checked:
painter.setBrush(QColor(0, 255, 0))
else:
painter.setBrush(QColor(255, 0, 0))
painter.drawRoundedRect(0, 0, self.width(), self.height(), self.height() // 2, self.height() // 2)
def mousePressEvent(self, event):
self.checked = not self.checked
self.update()
self.stateChanged.emit(self.checked)
```
步骤3:使用 SwitchButton 控件
```python
import sys
from PyQt5.QtWidgets import QApplication, QVBoxLayout, QLabel
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout()
label = QLabel('SwitchButton状态:')
switch = SwitchButton()
switch.stateChanged.connect(lambda state: label.setText('SwitchButton状态:{}'.format(state)))
layout.addWidget(label)
layout.addWidget(switch)
window.setLayout(layout)
window.show()
sys.exit(app.exec_())
```
运行上述代码,即可看到一个滑动开关控件。当您单击该控件时,它将在“开”和“关”状态之间切换,并发出一个信号。
阅读全文