PySide / PyQt detect if user trying to close window

断了今生、忘了曾经 提交于 2019-11-26 16:34:10

问题


is there a way to detect if user trying to close window? For example, in Tkinter we can do something like this:

def exit_dialog():
    #do stuff
    pass

root = Tk()
root.protocol("WM_DELETE_WINDOW", exit_dialog)
root.mainloop()

Thanks.


回答1:


Override the closeEvent method of QWidget in your main window.

For example:

class MainWindow(QWidget): # or QMainWindow
    ...

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

Another possibility is to use the QApplication's aboutToQuit signal like this:

app = QApplication(sys.argv)
app.aboutToQuit.connect(myExitHandler) # myExitHandler is a callable


来源:https://stackoverflow.com/questions/9249500/pyside-pyqt-detect-if-user-trying-to-close-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!