QFrame可以由其child元素触发吗

2024-03-29 14:42:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

它可能代表它里面的所有项目。在这个逻辑中,有没有什么方法可以满足我的需求?如果是的话。。怎么做


Tags: 项目selfui状态statusconnectgui按钮
1条回答
网友
1楼 · 发布于 2024-03-29 14:42:11

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

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)

相关问题 更多 >