Pyqt 防止组合框改变值

Pyqt prevent combobox change value

我在 PyQT4 中有四个组合框。如果用户更改第一个组合框中的值,则第二个组合框中的值也会更改,如果第二个组合框中的值发生更改,则类似地导致第三个组合框的更改,第四个组合框的情况相同。我想要的是,当我更改第一个组合框的值时,它应该只更改第二个组合框,而不会影响第三个和第四个组合框的更改。我如何在 PyQt 中做到这一点?

我在每个组合框上设置了 changedIndex 事件。

我无法为您提供确切的代码,但从概念上讲,您可以在全局级别设置一些标志,当您不想触发事件时,您可以简单地 return 函数调用而无需在第一行

大概是这样的

Boolean flag3rdCombo  = false;

function onchangesecondCombo(){

    if (flag3rdCombo){
        return;
    }

    .....

}

要防止对象在给定上下文中发出信号,您必须使用 blockSignals():

bool QObject.blockSignals (self, bool b)

If block is true, signals emitted by this object are blocked (i.e., emitting a signal will not invoke anything connected to it). If block is false, no such blocking will occur.

The return value is the previous value of signalsBlocked().

Note that the destroyed() signal will be emitted even if the signals for this object have been blocked.

为了简化任务,setCurrentIndex() 方法将被覆盖。

class ComboBox(QComboBox):
    def setCurrentIndex(self, ix):
        self.blockSignals(True)
        QComboBox.setCurrentIndex(self, ix)
        self.blockSignals(False)

下面的例子展示了它的用法:

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setLayout(QVBoxLayout())

        l = [str(i) for i in range(5)]
        cb1 = ComboBox(self)
        cb1.addItems(l)

        cb2 = ComboBox(self)
        cb2.addItems(l)

        cb3 = ComboBox(self)
        cb3.addItems(l)

        cb4 = ComboBox(self)
        cb4.addItems(l)

        cb1.currentIndexChanged.connect(cb2.setCurrentIndex)
        cb2.currentIndexChanged.connect(cb3.setCurrentIndex)
        cb3.currentIndexChanged.connect(cb4.setCurrentIndex)

        self.layout().addWidget(cb1)
        self.layout().addWidget(cb2)
        self.layout().addWidget(cb3)
        self.layout().addWidget(cb4)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())