gpt4 book ai didi

python - QCheckbox 检查所有其他 QCheckBoxes

转载 作者:行者123 更新时间:2023-12-04 01:49:18 25 4
gpt4 key购买 nike

我的问题与这篇文章非常相似,Python PyQt - Checkbox to uncheck all other checkboxes .但是,我试图在选中主复选框时选中所有其他框,同时,如果独立选中任何其他框,那么我想取消选中主复选框。我尝试修改提供的答案,但无法理解“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_())

关于python - QCheckbox 检查所有其他 QCheckBoxes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54014436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com