Connecting signal to slot immediately causes signal to be emitted

前端 未结 3 1227
不思量自难忘°
不思量自难忘° 2021-01-24 12:34

I am writing a program with python 3.3.3 and pyqt5. I have connected many signals and slots with no problem. This one is causing a problem. My code follows:

          


        
3条回答
  •  自闭症患者
    2021-01-24 13:05

    Building on ekhumoro's answer, you could also let the signal pass the currentText to the lambda function. This means you would just pass the text into the function and not have to get the currentText later.

    def _vendorChanged(vendorText, vendorsDict, modelCBox):
    
        modelsList = vendorsDict[vendorText]
    
        added_models = []
    
        modelCBox.clear()
        for rclass in modelsList:
            if rclass.MODEL not in added_models:
                added_models.append(rclass.MODEL)
        print("adding to modelCB")
        modelCBox.addItems(sorted(added_models))
        print("Done adding to modelCB")
    
    vendorComboBox.currentTextChanged[str].connect(
        lambda vendorText: _vendorChanged(vendorText, dictVendors, modelComboBox))
    

    Also, if you don't need the references to dictVendors and modelComboBox to update based on the current scope of the lambda function every time the signal is emitted, you could leave them out of the parameter list and let the _vendorChanged function simply inherit them from it's parent scope (which is the same as the lambda's parent scope... so I'm not sure there's be any difference...). The appeal of this is that you no longer need the lamda to provide the signal with a callable... you can give it the _vendorChanged function directly:

    def _vendorChanged(vendorText):
    
        modelsList = dictVendors[vendorText]
    
        added_models = []
    
        modelComboBox.clear()
        for rclass in modelsList:
            if rclass.MODEL not in added_models:
                added_models.append(rclass.MODEL)
        print("adding to modelCB")
        modelComboBox.addItems(sorted(added_models))
        print("Done adding to modelCB")
    
    vendorComboBox.currentTextChanged[str].connect(_vendorChanged)
    

    Hope that helps!

提交回复
热议问题