0

I know how this can be done OOP style, but am interested in fully understanding PyQt by seeing how the GUI toolkit can be programmed in both an object orientated and a procedural way.

My question is how can I bind the application closing event (click app cross) to the function in the code below? How can it be called when the application is quit?

import sys
from PyQt5.QtWidgets import (QWidget, QToolTip,
    QPushButton, QApplication, QMessageBox)
from PyQt5.QtGui import QFont


def closeEvent(event):
    reply = QMessageBox.question(w, 'Message',
        "Are you sure to quit?", QMessageBox.Yes |
        QMessageBox.No, QMessageBox.No)

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

app = QApplication(sys.argv)

w = QWidget()

w.setGeometry(300, 300, 300, 200)
w.setWindowTitle('Procedural event binding - PyQt')
w.show()

sys.exit(app.exec_())

Thanks for your time.

1 Answer 1

1

You could just overwrite the existing closeEvent of the widget:

w.closeEvent = closeEvent

and that will work in your example.

If you want a bound method, you can do:

import types
...

def closeEvent(self, event):
    reply = QMessageBox.question(self, 'Message',
    ...

w.closeEvent = types.MethodType(closeEvent, w)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.