Max
Max

Reputation: 2162

PyQt5 QWidget code uses un-initialized variable

I am following a tutorial on zetcode.com and I seem to have run into trouble. This code is supposed to be very straight forward and so I pasted it below.

This is all a part of an instance of the QWidget class (the base class of all UI objects). I have realized that this is one of the fundamental classes I need to understand in order to write a GUI, and I am simply puzzled on what is going on in the program.

The program is simple enough: PyQt opens a window, you are then able to exit out of that window via the 'x' button. And upon clicking the 'x' a message inquiring "Are you sure to quit?" allows you to continue to exit or cancel.

import sys
from PyQt5.QtWidgets import QWidget, QMessageBox, QApplication


class Example(QWidget):

def __init__(self):
    super().__init__()

    self.initUI()


def initUI(self):

    self.setGeometry(300, 300, 250, 150)
    self.setWindowTitle('Message box')
    self.show()

def closeEvent(self, event):

    reply = QMessageBox.question(self, 'Message',
        "Are you sure to quit?", QMessageBox.Yes |
        QMessageBox.No, QMessageBox.No)

    if reply == QMessageBox.Yes:
        event.accept()
    else:
        event.ignore()


if __name__ == '__main__':

app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())

So what doesn't make sense? The closeEvent() method that QWidget calls. The method seemingly accepts a variable "event" that is never initialized but somehow passed into the function. The methods "event.accept()" and "event.ignore()" are then called on an object that previously was never initialized.

I am a noob in PyQt/Qt and maybe it's a misunderstanding of Python too. Here is documentation on the function http://doc.qt.io/qt-5/qwidget.html#closeEvent, that may clarify things.

Upvotes: 0

Views: 331

Answers (1)

Mel
Mel

Reputation: 6075

The method seemingly accepts a variable "event" that is never initialized but somehow passed into the function.

That is how a method works. Consider this simple function:

def print_a_word(word):
   print(word)

It takes an argument word, that we did not initialized. When you call the function, then you need to define what word is:

word = "unicorn"
print_a_word(word)

If you look at the doc in more details, you'll see that event is a QCloseEvent, and it is "initialized" somewhere else in QWidget

The QCloseEvent class contains parameters that describe a close event.

Close events are sent to widgets that the user wants to close, usually by choosing "Close" from the window menu, or by clicking the X title bar button. They are also sent when you call QWidget::close() to close a widget programmatically.

Upvotes: 2

Related Questions