QCheckBox Widget in PyQt6

There are various ways to create a Check Box in PyQt6, Usually, we use Check Box in forms, settings panels, multi-selection UIs, etc to select multiple options from a given group.

In this tutorial, I am going to explain to you various methods of creating a Check Box in PyQt6. I will also explain how to organize Checkboxes in layouts and styling QCheckBox with QSS.

Let us start learning from the introduction of the QCheckBox Widget in PyQt6.

QCheckBox Widget in PyQt6

QCheckBox is a widget in PyQt6 that creates a checkbox option that can be toggled on (checked) or off (unchecked). You can select more than one checkbox at the same time, unlike radio buttons where you can only choose one option.

Common Use Cases:

  • Enable/disable features
  • Set user preferences
  • Create “remember me” options on login forms
  • Create “agree to terms” confirmations

If you are new to learn PyQt6 you can see How to Install PyQt6 on Different Platforms? article to set up PyQt6 in your system.

Create QCheckBox Widget in PyQt6

Let me explain various methods to create QCheckBox widget in PyQt6.

Method 1: Basic Creation

The Basic Creation method is the simplest way to create a checkbox in PyQt6. You just use the QCheckBox class directly and provide a label text.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QCheckBox

class CheckboxDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Basic Checkbox Example")
        self.setGeometry(100, 100, 300, 150)
        
        # Create layout
        layout = QVBoxLayout()
        
        # Basic creation of a checkbox
        checkbox = QCheckBox("Enable notifications")
        
        # Add to layout
        layout.addWidget(checkbox)
        
        # Set the layout
        self.setLayout(layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = CheckboxDemo()
    window.show()
    sys.exit(app.exec())

I executed the above example code and added the screenshot below.

QCheckBox Widget in PyQt6

In this example, we create a simple checkbox with the label “Enable notifications”. The checkbox is created by directly using the QCheckBox class and passing the desired text label.

Check out Handle Button Click Events Using Signals and Slots in PyQt6

Method 2: Create CheckBox with Icon in PyQt6

Here’s a simple PyQt6 example where we create a checkbox that includes an icon

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QCheckBox
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import QSize 

class CheckboxWithIconDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Checkbox with Icon Example")
        self.setGeometry(100, 100, 300, 150)
        
        # Create layout
        layout = QVBoxLayout()
        
        # Create checkbox with icon
        checkbox = QCheckBox("Enable notifications")
        
        # Set icon for the checkbox
        icon = QIcon("bell.png")  # Make sure this image exists in your directory
        checkbox.setIcon(icon)
        
        # Set icon size
        checkbox.setIconSize(QSize(24, 24))
        
        # Add to layout
        layout.addWidget(checkbox)
        
        # Set the layout
        self.setLayout(layout)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = CheckboxWithIconDemo()
    window.show()
    sys.exit(app.exec())

I executed the above example code and added the screenshot below.

Create QCheckBox Widget in PyQt6

This code creates a checkbox with both a text label (“Enable notifications”) and an icon. The icon is set using the setIcon() method, and its size can be adjusted with setIconSize().

Read How to Arrange Widgets Using QGridLayout in PyQt6?

Method 3: Dynamically Create Checkboxes in a Loop

Creating checkboxes dynamically in a loop is useful when you need to create multiple checkboxes from a list of options or data that might change at runtime.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QCheckBox, QGroupBox

class DynamicCheckboxesDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Dynamic Checkboxes Example")
        self.setGeometry(100, 100, 300, 250)
        
        # Create main layout
        main_layout = QVBoxLayout()
        
        # Create a group box for the checkboxes
        group_box = QGroupBox("Select Features:")
        checkbox_layout = QVBoxLayout()
        
        # List of options
        features = ["Dark Mode", "Auto-Save", "Spell Check", "Notifications", "Cloud Sync"]
        
        # Dynamically create checkboxes
        self.checkboxes = []  # Store references if needed later
        
        for feature in features:
            checkbox = QCheckBox(feature)
            
            # Connect signal to a slot (optional)
            checkbox.stateChanged.connect(self.on_state_changed)
            
            # Add to layout
            checkbox_layout.addWidget(checkbox)
            
            # Store reference
            self.checkboxes.append(checkbox)
        
        # Set the layout for the group box
        group_box.setLayout(checkbox_layout)
        
        # Add the group box to the main layout
        main_layout.addWidget(group_box)
        
        # Set the main layout
        self.setLayout(main_layout)
    
    def on_state_changed(self, state):
        # Get the checkbox that sent the signal
        sender = self.sender()
        if sender:
            print(f"{sender.text()}: {'Checked' if state == 2 else 'Unchecked'}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DynamicCheckboxesDemo()
    window.show()
    sys.exit(app.exec())

I executed the above example code and added the screenshot below.

PyQt6 QCheckBox Widget

This example demonstrates dynamically creating checkboxes from a list of features. The code loops through each feature in the list, create a checkbox for each one, and adds it to a layout.

Check out How to Use QVBoxLayout in PyQt6 for Vertical Layouts?

Checkboxes in Layouts

Organizing checkboxes using different layouts allows you to create structured and responsive interfaces. This example shows how to arrange checkboxes in various PyQt6 layout containers.

import sys
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                            QHBoxLayout, QGridLayout, QCheckBox, QGroupBox, 
                            QLabel)

class CheckboxLayoutsDemo(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Checkbox Layouts Example")
        self.setGeometry(100, 100, 500, 400)
        
        # Create central widget
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # Main layout
        main_layout = QVBoxLayout(central_widget)
        
        # 1. Vertical Layout Example
        vbox_group = QGroupBox("Vertical Layout")
        vbox = QVBoxLayout()
        
        vbox.addWidget(QCheckBox("Option 1"))
        vbox.addWidget(QCheckBox("Option 2"))
        vbox.addWidget(QCheckBox("Option 3"))
        
        vbox_group.setLayout(vbox)
        main_layout.addWidget(vbox_group)
        
        # 2. Horizontal Layout Example
        hbox_group = QGroupBox("Horizontal Layout")
        hbox = QHBoxLayout()
        
        hbox.addWidget(QCheckBox("Red"))
        hbox.addWidget(QCheckBox("Green"))
        hbox.addWidget(QCheckBox("Blue"))
        
        hbox_group.setLayout(hbox)
        main_layout.addWidget(hbox_group)
        
        # 3. Grid Layout Example
        grid_group = QGroupBox("Grid Layout")
        grid = QGridLayout()
        
        # Add checkboxes in a grid pattern
        grid.addWidget(QCheckBox("Top-Left"), 0, 0)
        grid.addWidget(QCheckBox("Top-Right"), 0, 1)
        grid.addWidget(QCheckBox("Bottom-Left"), 1, 0)
        grid.addWidget(QCheckBox("Bottom-Right"), 1, 1)
        
        grid_group.setLayout(grid)
        main_layout.addWidget(grid_group)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = CheckboxLayoutsDemo()
    window.show()
    sys.exit(app.exec())

This example showcases three different ways to organize checkboxes:

  1. Vertical Layout (QVBoxLayout): Stacks checkboxes vertically, one below another. This is useful for lists of options.
  2. Horizontal Layout (QHBoxLayout): Arranges checkboxes side by side horizontally. Good for a small set of related options.
  3. Grid Layout (QGridLayout): Positions checkboxes in a table-like grid with rows and columns. Useful for creating forms or when you need more structured spatial organization.

Read QHBoxLayout in PyQt6 for Horizontal Layouts

Styled QCheckBox with QSS (Qt Style Sheets)

Qt Style Sheets (QSS) allow you to customize the appearance of checkboxes using CSS-like syntax. You can change colors, sizes, and even replace the default checkbox indicator with custom graphics.

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QCheckBox, QLabel

class StyledCheckboxDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Styled Checkboxes Example")
        self.setGeometry(100, 100, 350, 300)
        
        # Create layout
        layout = QVBoxLayout()
        
        # Add a title
        layout.addWidget(QLabel("Customized Checkboxes:"))
        
        # Create several checkboxes with different styles
        checkbox1 = QCheckBox("Bold Blue Checkbox")
        checkbox1.setObjectName("blueCheckbox")
        
        checkbox2 = QCheckBox("Green Checkbox with Custom Size")
        checkbox2.setObjectName("greenCheckbox")
        
        checkbox3 = QCheckBox("Red Rounded Checkbox")
        checkbox3.setObjectName("redCheckbox")
        
        checkbox4 = QCheckBox("Custom Indicator Checkbox")
        checkbox4.setObjectName("customIndicator")
        
        # Add to layout
        layout.addWidget(checkbox1)
        layout.addWidget(checkbox2)
        layout.addWidget(checkbox3)
        layout.addWidget(checkbox4)
        
        self.setLayout(layout)
        
        # Apply styles using QSS
        self.setStyleSheet("""
            /* Blue checkbox with bold text */
            #blueCheckbox {
                font-weight: bold;
                color: #0066cc;
            }
            
            /* Green checkbox with larger indicator */
            #greenCheckbox {
                color: #008800;
            }
            #greenCheckbox::indicator {
                width: 20px;
                height: 20px;
            }
            
            /* Red checkbox with rounded corners */
            #redCheckbox {
                color: #cc0000;
            }
            #redCheckbox::indicator {
                border-radius: 6px;
                border: 2px solid #cc0000;
            }
            #redCheckbox::indicator:checked {
                background-color: #cc0000;
                image: url(checkmark.png); /* Optional custom checkmark */
            }
            
            /* Custom indicator checkbox */
            #customIndicator::indicator:unchecked {
                image: url(unchecked.png); /* Replace with your image path */
                width: 24px;
                height: 24px;
            }
            #customIndicator::indicator:checked {
                image: url(checked.png); /* Replace with your image path */
                width: 24px;
                height: 24px;
            }
        """)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = StyledCheckboxDemo()
    window.show()
    sys.exit(app.exec())

This example demonstrates how to use QSS to customize checkboxes in various ways:

  1. Simple Styling: Changing text color and font weight for checkbox1
  2. Size Modification: Making the checkbox indicator larger for checkbox2
  3. Shape and Color: Create a rounded checkbox with a custom border and fill color for checkbox3
  4. Custom Images: Completely replacing the default indicator with custom images for checkbox4

Related articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.