python - 如何连接两个 QLineEdit 以具有相同的输入(由 QCheckBox 控制)
问题描述
我有两个行编辑(le_A
和le_B
),它们只接受数值和一个复选框(chk_box
)。每当检查时,我都会在获得le_A
和le_B
拥有相同的输入(请参见下面的方案2) (在哪里'Controller')时遇到问题。chk_box
chk_box
示例场景:
场景 1. 用户可以输入任何值,
le_A
或者le_B
当它被取消选中时。例如,输入值为le_A
10,而le_B
值为 20。场景 2. 用户输入的任何值,
le_A
并且le_B
在选中时将是相同的。例如,如果我在 中输入 10,则为le_A
10。le_B
输入 done in 也是如此le_B
- 相同的值将显示在 中le_A
。
代码:
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)
推荐阅读
- heroku - 更改 Heroku 服务器
- r - 汇总不同聚合级别的数据 - R 和 tidyverse
- python - 使用 scipy.optimize 的 Python 约束非线性优化无法找到最佳解决方案
- azure - 如何在 Visual Studio Code 上本地运行/调试 Azure 云服务?
- react-native - 有没有办法判断何时看到反应组件?
- python - 在 Linux 中使用 Python 而不是命令行导出环境变量
- c# - MySQL IN 子句:当我多次使用相同的值时,如何获得多行?
- c++ - 在编译时收到未初始化的内存警告
- javascript - React Redux this.props 总是返回 undefined
- c - c语言中带有fork的udp服务器多进程