我的问题与这篇文章非常相似,Python PyQt - 复选框取消选中所有其他复选框。但是,当选中主复选框时,我正在尝试选中所有其他框,同时,如果单独选择任何其他框,那么我想取消选择主复选框。我尝试修改提供的答案,但无法绕过"self.sender"信号。取消选中复选框时,我无法更改选择。这是我使用 @ eyllanesc 提供的解决方案修改的代码。任何帮助都非常感谢,谢谢!
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class Test(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.checkBoxAll = QCheckBox("Select All")
self.checkBoxA = QCheckBox("Select A")
self.checkBoxB = QCheckBox("Select B")
self.checkBoxAll.setChecked(False)
self.checkBoxAll.stateChanged.connect(self.onStateChange)
self.checkBoxA.stateChanged.connect(self.onStateChange)
self.checkBoxB.stateChanged.connect(self.onStateChange)
grid = QGridLayout(self)
grid.addWidget(self.checkBoxAll, 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.checkBoxAll:
self.checkBoxA.setChecked(True)
self.checkBoxB.setChecked(True)
elif self.sender() in (self.checkBoxA, self.checkBoxB):
self.checkBoxAll.setChecked(False)
根据您拥有的逻辑,您正在创建一个循环,因为任何元素的状态更改都会更改另一个元素的状态,这个想法是使用 blockSignals() 在插槽中实现状态更改时阻止信号的发射:
from PyQt5 import QtCore, QtGui, QtWidgets
class Test(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.checkBoxAll = QtWidgets.QCheckBox("Select All")
self.checkBoxAll.setChecked(False)
self.checkBoxAll.stateChanged.connect(self.onStateChangePrincipal)
self.checkBoxA = QtWidgets.QCheckBox("Select A")
self.checkBoxB = QtWidgets.QCheckBox("Select B")
self.checkboxes = [self.checkBoxA, self.checkBoxB]
for checkbox in self.checkboxes:
checkbox.stateChanged.connect(self.onStateChange)
grid = QtWidgets.QGridLayout(self)
grid.addWidget(self.checkBoxAll, 1, 0)
grid.addWidget(self.checkBoxA, 2, 0)
grid.addWidget(self.checkBoxB, 3, 0)
self.setWindowTitle('Test')
@QtCore.pyqtSlot(int)
def onStateChangePrincipal(self, state):
if state == QtCore.Qt.Checked:
for checkbox in self.checkboxes:
checkbox.blockSignals(True)
checkbox.setCheckState(state)
checkbox.blockSignals(False)
@QtCore.pyqtSlot(int)
def onStateChange(self, state):
self.checkBoxAll.blockSignals(True)
self.checkBoxAll.setChecked(QtCore.Qt.Unchecked)
self.checkBoxAll.blockSignals(False)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Test()
w.show()
sys.exit(app.exec_())