Pyqt prevent combobox change value

后端 未结 2 1918
囚心锁ツ
囚心锁ツ 2020-12-21 08:31

I have four combo-box boxes that in PyQT4. If user change the value in first combo-box the values from second are altered and similarly if the value in seco

2条回答
  •  盖世英雄少女心
    2020-12-21 09:09

    To prevent an object from issuing signals in a given context you must use 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.

    To simplify the task, the setCurrentIndex() method will be overwritten.

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

    The following example shows its use:

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

提交回复
热议问题