pythonpyqtpyqt5qt-signalsqt-slot

Optional Signal Arguments


I have a function which has default keyword arguments. I'm having trouble implementing this as I keep getting an error that if my signal has two arguments then I need to pass both arguments. Is there any way around this?

class Controller(QWidget):
    trigger = pyqtSignal(str, str)
    def __init__(self):
        self.trigger.connect(self.myfunc)

    @pyqtSlot(str, str)
    def function(argument, optional_argument=''):
         do something

c = Controller()
c.trigger.emit('Hello', 'World') # This works
c.trigger.emit('Hello')  # This fails and says I need 2 arguments

Solution

  • You must make the connection pointing to signature in the connection besides overloading the types that the signal supports:

    import sys
    from PyQt5 import QtCore
    
    
    class Controller(QtCore.QObject):
        trigger = QtCore.pyqtSignal([str], [str, str])
    
        def __init__(self):
            super(Controller, self).__init__()
            self.trigger[str].connect(self.function)
            self.trigger[str, str].connect(self.function)
    
        @QtCore.pyqtSlot(str)
        @QtCore.pyqtSlot(str, str)
        def function(self, argument,  optional_argument=''):
            print(argument, optional_argument)
    
    
    def main():
        app = QtCore.QCoreApplication(sys.argv)
        c = Controller()
        c.trigger[str].emit('Hello')
        c.trigger[str, str].emit('Hello', 'World')
        QtCore.QTimer.singleShot(100, QtCore.QCoreApplication.quit)
        sys.exit(app.exec_())
    
    
    if __name__ == "__main__":
         main()