0

当一个项目(spinBox、LineEdit 等)在 GUI(通过设计器)中更改其值时,我设置了某个按钮的启用状态。例如:

self.ui.lineEdit_1.textChanged.connect(self.pushButton_status)
self.ui.checkBox_1.stateChanged.connect(self.pushButton_status)
self.ui.spinBox_1.valueChanged.connect(self.pushButton_status)
self.ui.spinBox_2.valueChanged.connect(self.pushButton_status)
self.ui.spinBox_3.valueChanged.connect(self.pushButton_status)
self.ui.spinBox_4.valueChanged.connect(self.pushButton_status)

这工作正常。虽然这里有很多行(实际代码中甚至更多)。我将所有这些项目都放在一个框架(QFrame)内。所以我想知道是否可以做类似的事情:

self.ui.frame_1.childValueChanged.connect(self.pushButton_status)

这可能代表其中的所有项目。在这个逻辑中有什么方法可以做我想要的吗?如果是这样..如何?

4

1 回答 1

1

没有直接的方法可以做你想做的事,但是有一种可维护的方法来做,在这种情况下,你只需要过滤小部件的类型,并通过在你的函数中添加更多选项来指示你将使用哪个信号案子:

def connectToChildrens(parentWidget, slot):
    # get all the children that are widget
    for children in parentWidget.findChildren(QtWidgets.QWidget): 
        # filter if the class that belongs to the object is QLineEdit
        if isinstance(children, QtWidgets.QLineEdit):
            # Connect the signal with the default slot.
            children.textChanged.connect(slot)
        elif isinstance(children, QtWidgets.QCheckBox):
            children.stateChanged.connect(slot)
        elif isinstance(children, QtWidgets.QSpinBox):
            children.valueChanged.connect(slot)

然后您可以通过以下方式使用它:

class MyDialog(QDialog):
    def __init__(self, parent=None): 
        super(MyDialog, self).__init__(parent) 
        self.ui = Ui_MyDialog() 
        self.ui.setupUi(self)
        connectToChildrens(self.ui.frame_1, self.pushButton_status)
于 2018-01-19T13:11:47.333 回答