Search code examples
pythoneventspyqt4signals-slots

Regarding the use of events


I'm building a GUI in python 2.7 with pyqt4. I wanted to link a button to a script and someone provided me the following code:

from PyQt4 import QtGui
import sys

# --- functions ---

def my_function(event=None):
    print 'Button clicked: event:', event
    print linetext.text()

    # run your code

# --- main ---

app = QtGui.QApplication(sys.argv)

window = QtGui.QWidget()

# add "layout manager"
vbox = QtGui.QVBoxLayout()
window.setLayout(vbox)

# add place for text
linetext = QtGui.QLineEdit(window)
vbox.addWidget(linetext)

# add button 
button = QtGui.QPushButton("Run", window)
vbox.addWidget(button)

# add function to button 
button.clicked.connect(my_function)

window.show()

sys.exit(app.exec_())

I don't understand why you would pass the event=None as an argument for my_function. When I run the script without the event parts it works fine.


Solution

  • It's not needed.

    In Qt, events and signals/slots are two separate systems. Generally speaking, events ultimately come from outside of the application (e.g. keyboard presses, mouse moves, etc), whilst signals come from within the application.

    A click is a combination of events (mouse-press + mouse-release), which are initially handled internally by Qt. The event handlers then emit the clicked signal whenever appropriate.

    The clicked signal actually sends its checked-state (i.e. True or False), rather than an event object. But that is not really relevant in your script (that is, you don't need to provide an argument for it).