Python Qt (PySide2) window.findChild() ran in loop overwriting reference

55 Views Asked by At

So I have a a set of 8 LineEdits and 8 Checkboxes as the following image. I'm trying to save some code and connect each check to enable/disable its corresponding line. image

It behaves fine if I set them individually, but saving code and writing a loop only the last checkbox/lineedit pair is working. It seems like the widget references are not evaluated in real-time but later on and only the last one is kept as I'm replacing the variable. Is this something related to PySide2 or python?

In the past have seen different widget behavior depending on which occasion app.exec_() was ran. Any thoughts why this happens?

Works as expected:

    le1 = w.findChild(QLineEdit, 'lineedit_addr1')
    check1 = w.findChild(QCheckBox, 'check_enabled1')
    check1.stateChanged.connect(lambda: le1.setEnabled(check1.isChecked()))
    le2 = w.findChild(QLineEdit, 'lineedit_addr2')
    check2 = w.findChild(QCheckBox, 'check_enabled2')
    check2.stateChanged.connect(lambda: le2.setEnabled(check2.isChecked()))
    
'...'
    le8 = w.findChild(QLineEdit, 'lineedit_addr8')
    check8 = w.findChild(QCheckBox, 'check_enabled8')
    check8.stateChanged.connect(lambda: le8.setEnabled(check8.isChecked()))

Only last check row works as expected:

    lineedits = [w.findChild(QLineEdit, 'lineedit_addr{}'.format(i)) for i in range(1,9)]
    checks = [w.findChild(QCheckBox, 'check_enabled{}'.format(i)) for i in range(1,9)]
    for le,check in zip(lineedits,checks):
        check.stateChanged.connect(lambda: le.setEnabled(check.isChecked()))
0

There are 0 best solutions below