16

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.

1 Answer 1

22

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.

4
  • Oh my, great example! :)
    – kuanyui
    Commented Aug 9, 2014 at 14:59
  • Bravo. Does this hopefully enable the death of 'lambda' in connect()? Commented Apr 4, 2015 at 21:38
  • You haven't used the pyqtSlot decorator. I've had seg faults go away after inserting that, so I would recommend adding it to mySignalHandler. Commented Aug 17, 2016 at 22:37
  • 1
    Also, your answer would be clearer if you didn't use wildcard imports. Commented Aug 17, 2016 at 22:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.