PyQt5 チュートリアル - チェックボックス

このチュートリアルでは、PyQt5 で QCheckBox
を学習します。QCheckBox
は、チェックまたはチェック解除できるオプションボタンです。ユーザーはチェックボックスグループから複数のオプションをチェックできます。
CheckBox
の例
import sys
from PyQt5.QtWidgets import (QWidget, QLabel, QHBoxLayout,QCheckBox, QApplication)
class basicWindow(QWidget):
def __init__(self):
super().__init__()
layout = QHBoxLayout()
self.setLayout(layout)
self.checkBoxA = QCheckBox("Select This.")
self.labelA = QLabel("Not slected.")
layout.addWidget(self.checkBoxA)
layout.addWidget(self.labelA)
self.setGeometry(200, 200, 300, 200)
self.setWindowTitle('CheckBox Example')
if __name__ == '__main__':
app = QApplication(sys.argv)
windowExample = basicWindow()
windowExample.show()
sys.exit(app.exec_())
どこ、
self.checkBoxA = QCheckBox("Select This.")
self.checkBoxA
は PyQt5 の QCheckBox
ウィジェットのインスタンスです。与えられたテキスト-Select This.
は CheckBox
の中空の四角の隣に表示されます。
CheckBox
イベント
基本的に、ユーザーはチェックボックスをオンまたはオフにし、状態変更信号に基づいてアクションを実行する必要があります。
import sys
from PyQt5.QtWidgets import (QWidget, QLabel, QHBoxLayout,QCheckBox, QApplication)
from PyQt5 import QtCore
class basicWindow(QWidget):
def __init__(self):
super().__init__()
layout = QHBoxLayout()
self.setLayout(layout)
self.checkBoxA = QCheckBox("Select This.")
self.labelA = QLabel("Not slected.")
self.checkBoxA.stateChanged.connect(self.checkBoxChangedAction)
layout.addWidget(self.checkBoxA)
layout.addWidget(self.labelA)
self.setGeometry(200, 200, 300, 200)
self.setWindowTitle('CheckBox Example')
def checkBoxChangedAction(self, state):
if (QtCore.Qt.Checked == state):
self.labelA.setText("Selected.")
else:
self.labelA.setText("Not Selected.")
if __name__ == '__main__':
app = QApplication(sys.argv)
windowExample = basicWindow()
windowExample.show()
sys.exit(app.exec_())
self.checkBoxA.stateChanged.connect(self.checkBoxChangedAction)
スロットメソッド checkBoxChangeAction()
を CheckBox stateChanged
シグナルに接続します。ユーザーがチェックボックスをオンまたはオフにするたびに、checkBoxChangeAction()
が呼び出されます。
def checkBoxChangedAction(self, state):
if (QtCore.Qt.Checked == state):
self.labelA.setText("Selected.")
else:
self.labelA.setText("Not Selected.")
state
引数は渡された CheckBox
の状態で、labelA
テキストは CheckBox
がチェックされている場合は Selected.
に、チェックされていない場合は Not Selected.
に変わります。
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn