Checkbox (QCheckbox) is part of Python PyQt (GUI module). It is the default PyQt widget to select an option, and a very typical widget when programming graphical user interfaces.

Its value can be either on (True) or off (False). Sometimes the analogy with a light switch is made, which does exactly the same type of behavior. It can be checked on startup with the method setChecked(true). It’s part of PyQt5.QtWidgets.

You can add a click callback / signal with .toggled.connect(). The receiving slot can then handle the event.

Related Course: Create GUI Apps with Python PyQt5

QCheckBox

PyQt Checkbox Example

A QCheckBox creates a checkbox with a text label. This button can be switched on (checked) or switched off (unchecked). They are often used to represent settings that can either be True or False.

For example, in the image below, you can select if the music should be on and if the movie should be played.

pyqt checkox

A checkbox is created with the line:

1
cbox = QCheckBox("I have a Cat")

A checkbox can be selected on start (by default its off), by calling the method .setChecked.

1
cbox.setChecked(True)

Each time a checkbox is clicked, it emits the signal stateChanged(). This signal can be connected to a callback function (which pyqt names slot), and you can run a Python function on clicked. Note that .toggled is used instead of .clicked.

1
cbox.toggled.connect(self.onClicked)       

Then you can create a method (in this case named onClicked) and handle the click there:

1
2
3
def onClicked(self):
cbutton = self.sender()
print("Animal " + (cbutton.animal) + " is " + str(cbutton.isChecked()))

The gui example below creates a checkbox in a PyQt window. If you click on the checkbox it will call the method onClicked(). The method .isChecked() can be used to get the checkbox state.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from PyQt5.QtWidgets import *
import sys

class Window(QWidget):
def __init__(self):
QWidget.__init__(self)
layout = QGridLayout()
self.setLayout(layout)

cbutton = QCheckBox("I have a Cat")
cbutton.setChecked(True)
cbutton.animal = "Cat"
cbutton.toggled.connect(self.onClicked)
layout.addWidget(cbutton, 0, 0)

def onClicked(self):
cbutton = self.sender()
print("Animal " + (cbutton.animal) + " is " + str(cbutton.isChecked()))

app = QApplication(sys.argv)
screen = Window()
screen.show()
sys.exit(app.exec_())

If you are new to Python PyQt, then I highly recommend this book.

Download Examples