I have two line-edits (le_A
and le_B
) that only take numeric values and a check-box (chk_box
). I am having issues in getting le_A
and le_B
to have the same inputs (see Scenario 2 below) whenever chk_box
is checked (where chk_box
is the 'controller').
Example scenarios:
Scenario 1. User can input in any value in le_A
or le_B
when it is unchecked. For example, value in le_A
is 10, while le_B
is 20.
Scenario 2. Any values that User input in le_A
and le_B
will be the same when it is checked. For example, if I input 10 into le_A
, le_B
will be 10. And the same goes for input done in le_B
- the same value will be shown in le_A
.
Code:
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_())
So if I understand your requirements correctly, when the checkbox is checked, you want to synchronise the text of the line-edits - and then also keep them the same whenever the user enters any new text. If so, the following changes will achieve that:
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)