[파이썬] PyQt 체크 박스 (`QCheckBox`) 위젯

In this blog post, we will explore how to use the QCheckBox widget in PyQt to create interactive checkboxes in our Python GUI applications.

Introduction to QCheckBox

The QCheckBox widget is a PyQt class that represents a standard checkbox control. It allows the user to either select or deselect a particular option. This widget is commonly used in forms, preference settings, and other areas where binary choices need to be made.

Creating a QCheckBox

To create a QCheckBox in PyQt, we need to import the relevant classes and modules. The following code snippet demonstrates how to create a simple checkbox:

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

class CheckBoxExample(QWidget):
    def __init__(self):
        super().__init__()

        self.init_ui()

    def init_ui(self):
        self.layout = QVBoxLayout()

        self.checkbox = QCheckBox('Enable Option', self)
        self.checkbox.stateChanged.connect(self.checkbox_state_changed)

        self.layout.addWidget(self.checkbox)

        self.setLayout(self.layout)

    def checkbox_state_changed(self, state):
        if state == 2:  # Checked
            print("Option enabled")
        else:
            print("Option disabled")

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

Explanation of the Code

Conclusion

In this blog post, we learned how to use the QCheckBox widget in PyQt to create interactive checkboxes in our Python GUI applications. We explored the creation of a QCheckBox and handling its state changes. By incorporating checkboxes into our applications, we can provide users with convenient options for selecting or deselecting specific settings or choices.

Feel free to explore more features and configurations available for the QCheckBox widget in the official PyQt documentation.