PyQt QCheckBox

The QCheckBox widget provides buttons with two states: on/off. This widget provides a checkbox with one text label. (See QCheckBox official documentation)

When the check box is selected or turned off, a stateChanged() signal occurs. You can connect this signal to a specific slot whenever you want to cause any action whenever the status of the check box changes.

QCheckBox.

You can also use the isChecked() method to determine whether a check box is selected. Returns a boolean value, depending on whether selected or not.

A typical check box has only an optional/off state, but the setTristate() method allows you to have a 'no change' state. This check box is useful for give users the option to select or not to select.

qcheckbox pyqt checkbox

Related course: Create Desktop Apps with Python PyQt5

Use the checkState() method to obtain the state of a check box that has three states. Returns a value of 2/1/0, respectively, depending on whether selected/changed/turned off.

The QButtonGroup class allows you to create a group of exclusive/non-exclusive buttons by grouping multiple buttons. A group of exclusive buttons can only select one of several buttons.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QCheckBox
from PyQt5.QtCore import Qt

class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        cb = QCheckBox('Show title', self)
        cb.move(20, 20)
        cb.toggle()
        cb.stateChanged.connect(self.changeTitle)

        self.setWindowTitle('QCheckBox')
        self.setGeometry(300, 300, 300, 200)
        self.show()

    def changeTitle(self, state):
        if state == Qt.Checked:
            self.setWindowTitle('QCheckBox')
        else:
            self.setWindowTitle(' ')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

I created a checkbox and when it was checked, the letter 'QCheckBox' appeared in the title bar.

Depending on the status of the checkbox, the title appears and disappears.

Description

cb = QCheckBox('Show title', self)

Create a checkbox with the text label 'Show title'.

cb.toggle()

The checkbox appears off by default, so we used the toggle() method to replace it with an on state.

cb.stateChanged.connect(self.changeTitle)

Connect the stateChanged method that occurs when the state of the checkbox changes to the changeTitle() method we defined.

def changeTitle(self, state):

    if state == Qt.Checked:
        self.setWindowTitle('QCheckBox')
    else:
        self.setWindowTitle(' ')

The state of the checkbox is given as a parameter of the changeTitle() method.

If checked, the title will be represented as a 'QCheckBox' or as an empty string.

Related course: Create Desktop Apps with Python PyQt5