class MainWindow(QWidget): # or QMainWindow ... def closeEvent(self, event): # do stuff if can_exit: event.accept() # let the window close else: event.ignore()