【问题标题】:How to connect two QLineEdit to have the same inputs (controlled by a QCheckBox)如何连接两个 QLineEdit 以具有相同的输入(由 QCheckBox 控制)
【发布时间】:2019-11-19 19:15:01
【问题描述】:

我有两个行编辑(le_Ale_B),它们只接受数值和一个复选框(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').

示例场景:

  • 场景一、用户可以在le_Ale_B不勾选时输入任意值。例如,le_A 中的值为 10,而le_B 中的值为 20。

  • 场景 2. 用户在 le_Ale_B 中输入的任何值在选中时都将相同。例如,如果我在le_A 中输入 10,le_B 将是 10。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_())

【问题讨论】:

    标签: python pyqt4 signals-slots qlineedit qcheckbox


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 是的,这就是我要找的!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 2017-03-10
    相关资源
    最近更新 更多