pythonsignalspyqt4signals-slots

Define pyqt4 signals with a list as argument


According to

http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html

I can define a pyqt4-signal with takes an integer argument by mysignal = pyqtSignal(int). How can I define a signal which takes an integer and a list of strings or more generally of an object called myobject as argument.


Solution

  • The following code creates a signal which takes two arguments: an integers and a list of objects. The UI contains just a button. The signal is emitted when the button is clicked.

    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    from PyQt5.QtWidgets import *
    
    class Foo(object):
        pass
    
    class MyWidget(QWidget):
        mysignal = pyqtSignal(int, list)
        
        def __init__(self, parent=None):
            super(MyWidget, self).__init__(parent)
            self.hlayout = QHBoxLayout()
            self.setLayout(self.hlayout)
            self.b = QPushButton("Emit your signal!", self)
            self.hlayout.addWidget(self.b)
            self.b.clicked.connect(self.clickHandler)
            self.mysignal.connect(self.mySignalHandler)
        
        def clickHandler(self):
            self.mysignal.emit(5, ["a", Foo(), 6])
    
        def mySignalHandler(self, n, lst):
            print(n)
            print(lst)
    
    if __name__ == '__main__':
        import sys
        app = QApplication(sys.argv)
        w = MyWidget()
        w.show()
        sys.exit(app.exec_())
    

    When clicking the button you should see something like:

    5
    ['a', <__main__.Foo object at 0xb7423e0c>, 6]
    

    on your terminal.