Define pyqt4 signals with a list as argument

student picture student · Dec 23, 2012 · Viewed 12.2k times · Source

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.

Answer

Vicent picture Vicent · Dec 23, 2012

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 PyQt4.QtGui import *
from PyQt4.QtCore 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, l):
        print n
        print l

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.