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)
我們將 slot
方法 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
文字將變為 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