Adding action to CheckBox using PyQt5


Graphical User Interface (GUI) frameworks provide developers with the tools and capabilities to create visually appealing and interactive applications. PyQt5, a Python binding for the Qt framework, offers a robust toolkit for building GUI applications with ease. Among the fundamental components offered by PyQt5 is the CheckBox, a widget that allows users to select or deselect an option.

By adding actions to CheckBoxes, we can enhance the functionality and interactivity of our applications. This feature enables us to perform specific tasks or trigger events based on the state of the CheckBox. Whether it is enabling or disabling a feature, updating a user interface element, or triggering a function, the ability to add actions to CheckBoxes empowers developers to create more dynamic and responsive applications.

Prerequisites

Before we begin, ensure that you have the following prerequisites installed on your machine 

  • Python (version 3.6 or higher)

  • PyQt5 library (can be installed via pip install pyqt5)

Step 1: Importing the Necessary Libraries

Let's start by importing the required libraries for our PyQt5 application 

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QCheckBox

In this section, we start by importing the necessary libraries for our PyQt5 application. We import sys to handle system-specific functionality and QApplication, QMainWindow, QWidget, and QCheckBox from the QtWidgets module of PyQt5. These classes provide the foundation for creating the GUI elements of our application.

Step 2: Creating the Main Window

To create a window for our application, we'll define a class that inherits from QMainWindow −

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("CheckBox Action Example")
        self.setGeometry(100, 100, 300, 200)

        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)

Here, we define a class MainWindow that inherits from QMainWindow. The MainWindow class represents the main window of our application. In the __init__ method, we call the parent class constructor using super().__init__() to initialize the QMainWindow. Then, we call the initUI() method, which sets up the initial user interface.

In the initUI() method, we set the title of the window using self.setWindowTitle(). We also set the size and position of the window using self.setGeometry(). The arguments of setGeometry() are the x-coordinate, y-coordinate, width, and height of the window.

Next, we create a central widget using self.central_widget = QWidget(self). The central widget acts as a container for other widgets and is set as the central widget of the main window using self.setCentralWidget(self.central_widget).

Step 3: Adding a CheckBox

Next, let's add a CheckBox widget to our main window. This widget will serve as the basis for our action implementation 

self.checkbox = QCheckBox("Enable Action", self.central_widget)
self.checkbox.setGeometry(50, 50, 200, 30)

In this section, we create a QCheckBox widget named self.checkbox and add it to the central widget. The first argument of QCheckBox is the label text displayed next to the CheckBox, and the second argument is the parent widget.

We also set the geometry (position and size) of the CheckBox using self.checkbox.setGeometry(). The arguments of setGeometry() specify the x-coordinate, y-coordinate, width, and height of the CheckBox.

Step 4: Defining the Action

We will now define the action that should occur when the CheckBox state changes. In this example, we'll simply print a message based on whether the CheckBox is checked or unchecked 

def on_checkbox_change(state):
   if state == 2:  # Qt.Checked
       print("Action enabled!")
   else:
      print("Action disabled!")

self.checkbox.stateChanged.connect(on_checkbox_change)

Here, we define a function on_checkbox_change() that will be called when the state of the CheckBox changes. The function takes a state argument, which represents the new state of the CheckBox.

Inside the function, we check if the state is equal to Qt.Checked, which has a value of 2. If the CheckBox is checked, we print the message "Action enabled!". Otherwise, we print "Action disabled!".

We connect the stateChanged signal of the CheckBox to the on_checkbox_change() function using self.checkbox.stateChanged.connect(). This ensures that the function is called whenever the state of the CheckBox changes.

Step 5: Running the Application

To run the application, we need to instantiate the QApplication class and execute the event loop. Add the following code at the end of your script 

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

Finally, we have the code that runs the application. The if __name__ == "__main__": block ensures that the following code is only executed when the script is run directly and not imported as a module.

We create a QApplication instance app and pass sys.argv as an argument to handle command-line arguments. Then, we create an instance of the MainWindow class called window.

We call window.show() to display the main window. Lastly, we execute the application's event loop using app.exec(), and sys.exit() ensures a proper exit when the application is closed.

Step 6: Complete Code Example

Putting it all together, here's the complete code example 

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QCheckBox


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("CheckBox Action Example")
        self.setGeometry(100, 100, 300, 200)

        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)

        self.checkbox = QCheckBox("Enable Action", self.central_widget)
        self.checkbox.setGeometry(50, 50, 200, 30)

        def on_checkbox_change(state):
            if state == 2:  # Qt.Checked
                print("Action enabled!")
            else:
                print("Action disabled!")

        self.checkbox.stateChanged.connect(on_checkbox_change)


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

Step 7: Running the Application

Save the code to a file (e.g., checkbox_action.py) and run it using the command line 

python checkbox_action.py

You should see the application window with a CheckBox labeled "Enable Action." When you check or uncheck the CheckBox, the corresponding message will be printed to the console.

When you run the application and the window appears on the screen, you will see a CheckBox labeled "Enable Action". Initially, the CheckBox will be unchecked.

Scenario 1: CheckBox is Unchecked

If you click on the CheckBox to check it, you will see the following output in the console 

Action enabled!

Scenario 2: CheckBox is Checked

If you click on the CheckBox to uncheck it, you will see the following output in the console 

Action disabled!

These are the expected outputs based on the provided code. The program prints a corresponding message based on the state of the CheckBox. When the CheckBox is checked, it prints "Action enabled!", and when it is unchecked, it prints "Action disabled!".

Conclusion

In this article, we have successfully created a PyQt5 application that demonstrates how to add an action to a CheckBox. By utilizing the stateChanged signal of the CheckBox and connecting it to a custom function, you gained the ability to respond dynamically to user interactions. In the provided example, the function simply printed a message indicating whether the action was enabled or disabled based on the CheckBox state.

Updated on: 14-Aug-2023

332 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements