A checkbox is often a core part of a graphical user interface, it lets a user select from one or more options which can be either True or False. It can be created using the QCheckBox widget. When creating an new checkbox with the QCheckBox class, the first parameter is the label.

To apply actions to the toggle switch, we call .stateChanged.connect() followed by a callback method. When this method is called, it sends a boolean as state parameter. If checked, its the value QtCore.Qt.checked.

Related course: Create PyQt Desktop Appications with Python (GUI)

PyQt Checkbox example

To create a checkbox, first import QCheckBox from the module PyQt5.QtWidgets.

#https://pythonprogramminglanguage.com/pyqt-checkbox/
from PyQt5.QtWidgets import QCheckBox

Then create a new checkbox. As parameter you can set the text that is shown next to the checkbox.

box = QCheckBox("Awesome?",self)

You can change its position and size, by using the objects methods .move(x,y) and .resize(width,height).

box.move(20,20)
box.resize(320,40)
checkbox pyqt

You may also want to include a callback function, that reacts to checkbox clicks

box.stateChanged.connect(self.clickBox)

The Python PyQt example below creates a checkbox (QCheckBox) inside a window. If you click on the checkbox, it calls the method clickBox (toggled).

#https://pythonprogramminglanguage.com/pyqt-checkbox/
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QCheckBox, QWidget
from PyQt5.QtCore import QSize

class ExampleWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)

self.setMinimumSize(QSize(140, 40))
self.setWindowTitle("Checkbox")

self.b = QCheckBox("Awesome?",self)
self.b.stateChanged.connect(self.clickBox)
self.b.move(20,20)
self.b.resize(320,40)

def clickBox(self, state):

if state == QtCore.Qt.Checked:
print('Checked')
else:
print('Unchecked')

if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = ExampleWindow()
mainWin.show()
sys.exit( app.exec_() )

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

Download PyQt Examples