Search code examples
pyqtpysidesignals-slotsqspinbox

Python - How to pass a QSpinBox value together with other parameters to a slot?


It's quite straightforward to process a valueChanged signal of a single QSpinBox with a dedicated slot:

class MainWindow(QMainWindow):
        self.ui.spinbox.valueChanged.connect(self.slot)

    def slot(self,value):
        print(value)

Now imagine I have many spinboxes (e.g. each of them controls some parameter in a different instance of the same class) and would like to use the same slot to process them. I would like to do something like this:

class MainWindow(QMainWindow):
        self.ui.spinbox1.valueChanged.connect(lambda: self.slot(1))
        self.ui.spinbox2.valueChanged.connect(lambda: self.slot(2))
        self.ui.spinbox3.valueChanged.connect(lambda: self.slot(3))

    def slot(self,instance_id,value):
        ...

Unfortunately it doesn't work because the spinbox value is not passed through the lambda.

So, what is the best way to pass the value if I'd like to use one single slot to process many similar signals?


Solution

  • You can use the self.sender to identify the spinbox and get its value..

    class MainWindow(QMainWindow):
            self.ui.spinbox1.valueChanged.connect(self.slot)
            self.ui.spinbox2.valueChanged.connect(self.slot)
            self.ui.spinbox3.valueChanged.connect(self.slot)
    
        def slot(self):
            spinbox = self.sender()
            value = spinbox.value()