QPushButton两次点击设置不同checked状态
时间: 2024-05-14 17:15:58 浏览: 274
可以通过QPushButton的toggled信号和setChecked函数来实现。具体步骤如下:
1. 在初始化时,将QPushButton的初始状态设置为未选中状态(setChecked(False))。
2. 连接QPushButton的toggled信号到一个槽函数。
3. 在槽函数中判断当前的checked状态,如果为False则设置为True,如果为True则设置为False。
示例代码如下:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.button = QPushButton('Toggle', self)
self.button.setCheckable(True)
self.button.setChecked(False)
self.button.toggled.connect(self.on_toggle)
def on_toggle(self, checked):
if checked:
self.button.setText('ON')
else:
self.button.setText('OFF')
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
运行上述代码,点击按钮,按钮的checked状态会在选中和未选中之间切换,并且对应的文本也会发生变化。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)