QFrame可以由其子元素触发

时间:2018-01-19 12:54:47

标签: python pyqt5 qframe

当一个项目(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)

它可能代表它内部的所有物品。在这个逻辑中有什么方法可以做我想要的事情吗?如果是这样......怎么样?

1 个答案:

答案 0 :(得分: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)