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.

A checkbox is a box the user can tick. In PyQt that is QCheckBox. It holds two states, checked or not checked.

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.

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_() )

Reading the state

  • setChecked(True) ticks it from the start.
  • isChecked() returns True or False.
  • stateChanged is a signal with the new state as argument.
  • toggled fires on every click, stateChanged also fires when you set it in code.
  • QtCore.Qt.Checked and QtCore.Qt.Unchecked are the values you get in the signal.
  • setEnabled(False) greys it out so the user cannot change it.

A group of checkboxes where only one may be ticked is a radio button, not a checkbox. That is QRadioButton.

The fastest way to learn this is to write it yourself. The PyChallenge exercises run in your browser, no install needed.