QCheckBox复选框按钮控件是一种常用的用户界面控件,它提供了一个选中/取消选中的选项,可以用于多选和二选一的情况。在本文中,我们将介绍QCheckBox复选框按钮控件的常用API方法和信号,并给出一个简单的演示。
API方法和信号:
- setText(text: str):设置复选框按钮的文本
- setChecked(checked: bool):设置复选框按钮的选中状态
- isChecked() -> bool:返回复选框按钮的选中状态
- setTristate(y: bool):设置复选框按钮是否可以三态选择
- isTristate() -> bool:返回复选框按钮是否可以三态选择
- stateChanged.connect(slot):复选框按钮状态改变时触发该信号
下面是一个简单的演示,有一个QCheckBox复选框按钮控件,当选中该按钮时,程序窗口的背景颜色将改变。
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QCheckBox, QVBoxLayout
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.cbox = QCheckBox('Change Background Color', self)
self.cbox.move(50, 50)
self.cbox.setChecked(False)
vbox = QVBoxLayout()
vbox.addWidget(self.cbox)
self.setLayout(vbox)
self.cbox.stateChanged.connect(self.onCheckBoxStateChanged)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('QCheckBox')
self.show()
def onCheckBoxStateChanged(self, state):
if state == 2:
self.setStyleSheet('background-color: yellow')
else:
self.setStyleSheet('')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
在上面的代码中,我们创建了一个QCheckBox复选框按钮控件,文本为'Change Background Color'。在initUI()方法中,我们使用了一个垂直布局管理器来放置该复选框按钮控件。
我们通过连接stateChanged()信号和onCheckBoxStateChanged()方法来实现程序窗口背景颜色的改变。在onCheckBoxStateChanged()方法中,我们使用state参数来判断复选框按钮的选中状态,并设置相应的背景颜色。当复选框按钮被选中时,背景颜色为黄色;当复选框按钮未被选中时,背景颜色为默认颜色。