首页 > 解决方案 > 如何连接两个 QLineEdit 以具有相同的输入(由 QCheckBox 控制)

问题描述

我有两个行编辑(le_Ale_B),它们只接受数值和一个复选框(chk_box)。每当检查时,我都会在获得le_Ale_B拥有相同的输入(请参见下面的方案2) (在哪里'Controller')时遇到问题。chk_boxchk_box

示例场景:

代码:

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_())

标签: pythonpyqt4signals-slotsqlineeditqcheckbox

解决方案


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

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)

推荐阅读