如何连接两个 QLineEdit 以具有相同的输入(由 QCheckBox 控制)

How to connect two QLineEdit to have the same inputs (controlled by a QCheckBox)

我有两个只接受数值的行编辑(le_Ale_B)和一个复选框(chk_box)。每当检查 chk_box(其中 chk_box 是 'controller' ).

示例场景:

代码:

class CustomTest(QtGui.QWidget):
    def __init__(self, parent=None):
        super(CustomTest, self).__init__(parent)

        # Only numeric values
        self.le_A = QtGui.QLineEdit()        
        self.le_B = QtGui.QLineEdit()

        self.chk_box = QtGui.QCheckBox()

        lyt = QtGui.QHBoxLayout()
        lyt.addWidget(self.le_A)
        lyt.addWidget(self.le_B)
        lyt.addWidget(self.chk_box)

        self.setLayout(lyt)

        self.set_connections()

    def set_connections(self):
        self.chk_box.stateChanged.connect(self.chk_toggle)

    def chk_toggle(self):
        chk_value = self.chk_box.isChecked()
        a_val = self.le_A.text()
        b_val = self.le_B.text()

        # Inputs in either le_A and le_B should be the same
        if chk_value:
            # If the values are different, always use a_val as the base value
            if a_val != b_val:
                self.le_B.setText(str(b_val))
        else:
            # Inputs in either le_A and le_B can be different
            # Currently this is working
            pass

    if __name__ == "__main__":
        app = QtGui.QApplication(sys.argv)
        w = CustomTest()
        w.show()
        sys.exit(app.exec_())

因此,如果我正确理解了您的要求,选中复选框时,您希望同步行编辑的文本 - 然后在用户输入任何新文本时也保持它们相同。如果是这样,以下更改将实现这一点:

class CustomTest(QtGui.QWidget):
    ...
    def set_connections(self):
        self.chk_box.stateChanged.connect(self.change_text)
        self.le_A.textChanged.connect(self.change_text)
        self.le_B.textChanged.connect(self.change_text)

    def change_text(self, text):
        if self.chk_box.isChecked():
            sender = self.sender()
            if sender is self.chk_box:
                self.le_B.setText(self.le_A.text())
            elif sender is self.le_A:
                self.le_B.setText(text)
            else:
                self.le_A.setText(text)