SaltyCrane Blog — Notes on JavaScript and web development

PyQt: How to pass arguments while emitting a signal

I often forget how to do this so I'm documenting it here for future reference. If I want to emit a signal and also pass an argument with that signal, I can use the form self.emit(SIGNAL("mySignalName"), myarg). I connect the signal to a method in the usual way. To use the argument, I merely need to specify the argument in the method definition. What often confuses me is that I don't need to specify arguments in the connect statement. The example below emits a signal didSomething and passes two arguments, "important" and "information" to the update_label method.

import sys
import time
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 

#################################################################### 
class MyWindow(QWidget): 
    def __init__(self, *args): 
        QWidget.__init__(self, *args)

        self.label = QLabel(" ")
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        self.setLayout(layout)
        self.connect(self, SIGNAL("didSomething"),
                     self.update_label)
        self.do_something()

    def do_something(self):
        self.emit(SIGNAL("didSomething"), "important", "information")

    def update_label(self, value1, value2):
        self.label.setText(value1 + " " + value2)

####################################################################
if __name__ == "__main__": 
    app = QApplication(sys.argv) 
    w = MyWindow() 
    w.show() 
    sys.exit(app.exec_())

Comments


#1 Anonymous commented on :

Thanks. Struggled with that in the docs for ages.


#2 Fatih Arslan commented on :

Thanks for the tip, your blog is great, i really do benefit a lot of. Your examples are easy to understand and easy to follow.


#3 Peter Schmidtke commented on :

Thanks, finally an easy to understand post about user defined signals....not easy to find documentation for non informaticians ;)


#4 vl commented on :

Thanks! Finally I found understandable example!


#5 Danny commented on :

Thanks very much for providing this easy-to-understand example. You've really helped me a great deal.


#6 guillermo commented on :

Hi, i know this post is old, but i'm struggling with this problem and your solution help but in this example you are manually emitting the signal, how can i add arguments so signals emitted by the user interaction, or how can i read who emitted the signal? thank you very much


#8 Edlin commented on :

Thanks!!! It helps a lots~


#9 Pete Jemian commented on :

This example was very useful.

Changing the call of self.doSomething() to

QTimer.singleShot(3000, self.do_something)

will make the custom emit() more dramatic


#10 Szabolcs Illés commented on :

Should it work with PySide too ? Because when the last line ( self.do_something() is commented it brings up the window itself, when not it does nothing.

disqus:2159244016