Working with QCheckBox in PySide and PyQt: A Quick 2-Minute Tutorial

Posted by


PySide + PyQt are popular Python libraries that allow you to create graphical user interfaces (GUI) for your applications. In this tutorial, we will focus on the QCheckBox widget, which is a clickable box that can be checked or unchecked.

First, make sure you have PySide or PyQt installed on your system. You can easily install them using pip:

pip install PySide2

or

pip install PyQt5

Next, let’s create a simple GUI application with a QCheckBox widget. Create a new Python file and import the necessary libraries:

import sys
from PySide2.QtWidgets import QApplication, QWidget, QCheckBox

Now, let’s define our main window class:

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

    def initUI(self):
        self.setWindowTitle('QCheckBox Example')
        self.setGeometry(100, 100, 300, 200)

        self.checkbox = QCheckBox('Enable Feature', self)
        self.checkbox.move(20, 20)
        self.checkbox.stateChanged.connect(self.checkboxChanged)

    def checkboxChanged(self, state):
        if state == 2: # 2 corresponds to Checked state
            print('Feature enabled')
        else:
            print('Feature disabled')

In this code, we create a new MainWindow class that inherits from QWidget. We set the window title and size, and then create a QCheckBox widget with the label ‘Enable Feature’. We connect the stateChanged signal of the checkbox to the checkboxChanged method, where we print a message based on the checkbox state (checked or unchecked).

Finally, let’s create the application instance and run it:

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

This code creates a new QApplication instance, creates an instance of our MainWindow class, shows the main window, and starts the application event loop.

Now you can run your application and see the QCheckBox widget in action. You can click on the checkbox to toggle its state and see the corresponding messages in the console.

In this tutorial, we have covered the basics of using the QCheckBox widget in PySide + PyQt. You can further customize the appearance and behavior of the QCheckBox by exploring its documentation and experimenting with different properties and signals. Happy coding!

0 0 votes
Article Rating
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@MathTutorVideos
2 months ago

How about if you have three or 'n' checkboxes on one form and want only one to be selectable? So if oyu select A it deselects B and C and D and ….etc

@elsmok3952
2 months ago

Dude, PLEASE dont quit youtube

@wolfisraging
2 months ago

I love your these videos, keep doing them