我正在寻找一种方法来控制具有(父) QCheckBox的(子) QCheckBox。
在开始时,应该禁用子复选框,直到选中父复选框为止。
选中父chbox后,用户应该能够与子chbox进行交互。但是,如果父chbox未选中,则子chbox应重置为未选中状态。
以下是我到目前为止所拥有的代码
import os
import sys
from functools import partial
from PySide.QtCore import *
from PySide.QtGui import *
class TestDialog(QDialog):
def __init__(self):
super(TestDialog,self).__init__()
self.setWindowTitle('Checkbox Family')
self.initUI()
self.show()
def initUI(self):
# Checkboxes
parentChbox = QtGui.QCheckBox('Parent', self)
parentChbox.resize(parentChbox.sizeHint())
sonChbox = QtGui.QCheckBox('Son', self)
sonChbox.resize(sonChbox.sizeHint())
sonChbox.setEnabled(False)
sonChbox.setCheckState(Qt.Unchecked)
daughterChbox = QtGui.QCheckBox('Daughter', self)
daughterChbox.resize(daughterChbox.sizeHint())
daughterChbox.setEnabled(False)
daughterChbox.setCheckState(Qt.Unchecked)
# Layout
chboxLayout = QtGui.QHBoxLayout()
chboxLayout.addWidget(parentChbox)
chboxLayout.addWidget(sonChbox)
chboxLayout.addWidget(daughterChbox)
self.setLayout(chboxLayout)
# Event handling
parentChbox.stateChanged.connect(partial(self.parent_check, sonChbox))
def parent_check(self, childChbox):
if self.sender().isChecked():
childChbox.setEnabled(True)
else:
# [HELP] If the child checkbox becomes disabled, reset it to uncheck
if childChbox.isEnabled(False):
childChbox.setCheckState(Qt.Unchecked)
else:
pass
dia = TestDialog()我已经搜索了几天,找到了functools.partial和lambda,以便将子复选框作为额外的参数传递给slot方法。当我开始检查parentChbox时,会出现此错误
TypeError: parent_check() takes exactly 2 arguments (3 given)有没有人经历过这一点,你能给我一些前进的方向吗?
非常感谢。
发布于 2015-06-25 17:05:32
为了与复选框交互,应该将它们创建为TestDialog类的实例变量,如下所示:
def initUI(self):
self.parentChbox =QtGui.QCheckBox('Parent', self)
self.sonChbox =QtGui.QCheckBox('Son', self)
self.sonChbox.setEnabled(False)
self.sonChbox.setCheckState(QtCore.Qt.Unchecked)那么你就不需要partial或lambda了。您可以将self.parentChbox.stateChanged直接连接到函数parent_check。
check的stateChanged信号带有一个state参数,所以您可以这样做:
def parent_check(self,state):
if state==QtCore.Qt.Checked:
self.sonChbox.setEnabled(True)
else:
self.sonChbox.setEnabled(False)
self.sonChbox.setCheckState(QtCore.Qt.Unchecked)多亏了self,在Testdialog的任何方法中,你都可以轻松地访问你的复选框。
发布于 2015-06-25 18:04:17
用parentChbox.toggled.connect(lambda state: self.setState(state, sonChbox))替换parentChbox.stateChanged.connect(partial(self.parent_check, sonChbox))
然后将以下方法添加到您的类中
def setState(self, state, son):
son.setEnabled(state)
if not state:
son.setChecked(state)https://stackoverflow.com/questions/31045074
复制相似问题