In this tutorial, I am going to show you an example how to use the QCheckBox widget with PyQt5 in Python.

A checkbox is a small interactive box which you can click inside the box and toggle between the value between True and False.

Checkboxes are quite useful when you want to give a user a set of questions with Yes or No, True or False response.


Buy Me a Coffee? Your support is much appreciated!
PayPal Me: https://www.paypal.me/jiejenn/5
Venmo: @Jie-Jenn





Python Source Code:

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

class AppDemo(QWidget):
    def __init__(self):
        super().__init__()

        self.vLayout = QVBoxLayout()

        self.checkbox_A = QCheckBox('A')
        self.checkbox_B = QCheckBox('B')

        self.checkbox_A.stateChanged.connect(self.selectChkboxA)
        self.checkbox_B.stateChanged.connect(self.selectChkboxB)

        self.vLayout.addWidget(self.checkbox_A)
        self.vLayout.addWidget(self.checkbox_B)

        self.setLayout(self.vLayout)

    def selectChkboxA(self, checked):
        if Qt.Checked == checked:
            print('Checkbox A is checked')
        else:
            print('Checkbox A is unchecked')

    def selectChkboxB(self, checked):
        if Qt.Checked == checked:
            print('Checkbox B is checked')
        else:
            print('Checkbox B is unchecked')

if __name__ == '__main__':
    app = QApplication(sys.argv)

    demo = AppDemo()
    demo.show()

    app.exit(app.exec_())