我正在尝试进行一些验证,例如:
I'm trying to put in some validation such that:
但是当我运行此代码时,单击任何复选框都会取消选中 所有 3 个复选框.
But when I run this code, clicking any checkbox will uncheck all the 3 checkboxes.
即窗口初始化时选中了"None Selected".但是当我点击 "Select A" 时,它会取消选中 "None Selected",这是有意的,但没有得到 "Select A"检查.
i.e. The window initializes with "None Selected" checked. But when I click "Select A", it unchecks "None Selected", which is intended, but "Select A" doesn't get checked.
我做错了什么?
import sys
import PyQt5
class Test(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
checkBoxNone = QCheckBox("None Selected")
checkBoxA = QCheckBox("Select A")
checkBoxB = QCheckBox("Select B")
checkBoxNone.setChecked(True)
checkBoxNone.stateChanged.connect(lambda checked: (checkBoxA.setChecked(False), checkBoxB.setChecked(False)))
checkBoxA.stateChanged.connect(lambda checked: checkBoxNone.setChecked(False))
checkBoxB.stateChanged.connect(lambda checked: checkBoxNone.setChecked(False))
grid = QGridLayout()
grid.addWidget(checkBoxNone, 1, 0)
grid.addWidget(checkBoxA, 2, 0)
grid.addWidget(checkBoxB, 3, 0)
self.setLayout(grid)
self.setWindowTitle('Test')
self.show()
if __name__ == '__main__':
if not QApplication.instance():
app = QApplication(sys.argv)
else:
app = QApplication.instance()
ex = Test()
sys.exit(app.exec_())
问题是因为根据您的要求,只有在某些 QCheckBox
被勾选但您不做的情况下才应该做那些选项该验证,为了能够正确处理它,创建一个插槽并知道发出信号的对象,sender()
方法:
The problem is caused because according to your requirements, you should only make those options if some QCheckBox
is checked but you do not do that verification, to be able to handle it properly, create a slot and to know which object the signal was emited, the sender()
method:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Test(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.checkBoxNone = QCheckBox("None Selected")
self.checkBoxA = QCheckBox("Select A")
self.checkBoxB = QCheckBox("Select B")
self.checkBoxNone.setChecked(True)
self.checkBoxNone.stateChanged.connect(self.onStateChange)
self.checkBoxA.stateChanged.connect(self.onStateChange)
self.checkBoxB.stateChanged.connect(self.onStateChange)
grid = QGridLayout(self)
grid.addWidget(self.checkBoxNone, 1, 0)
grid.addWidget(self.checkBoxA, 2, 0)
grid.addWidget(self.checkBoxB, 3, 0)
self.setWindowTitle('Test')
self.show()
@pyqtSlot(int)
def onStateChange(self, state):
if state == Qt.Checked:
if self.sender() == self.checkBoxNone:
self.checkBoxA.setChecked(False)
self.checkBoxB.setChecked(False)
elif self.sender() in (self.checkBoxA, self.checkBoxB):
self.checkBoxNone.setChecked(False)
这篇关于取消选中所有其他复选框的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!