一个QCheckBox会有2种状态:选中和为选中。它由一个选择框和一个label组成,常常用来表示应用的某些特性是启用或不启用。

在下面的例子中,我们创建了一个选择框,它的状态变化会引起窗口标题的变化。

示例的执行效果如下:

QCheckBox控件-LMLPHP

 #!/usr/bin/python3
# -*- coding: utf- -*- """
ZetCode PyQt5 tutorial In this example, a QCheckBox widget
is used to toggle the title of a window. Author: Jan Bodnar
Website: zetcode.com
Last edited: August
""" from PyQt5.QtWidgets import QWidget, QCheckBox, QApplication
from PyQt5.QtCore import Qt
import sys class Example(QWidget): def __init__(self):
super().__init__() self.initUI() def initUI(self): cb = QCheckBox('Show title', self)
cb.move(, )
cb.toggle() # 设置默认是选中状态 # 将自定义的槽函数changeTitle和信号stateChanged绑定起来,
# 槽函数changeTitle会改变窗口的标题
cb.stateChanged.connect(self.changeTitle) self.setGeometry(, , , )
self.setWindowTitle('QCheckBox')
self.show() def changeTitle(self, state):
# 选中状态下,窗口标题设置为”QCheckBox”,否则设置为空
if state == Qt.Checked:
self.setWindowTitle('QCheckBox')
else:
self.setWindowTitle(' ') if __name__ == '__main__': app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
05-11 13:16