PySide/PyQt 检测用户是否尝试关闭窗口 [英] PySide / PyQt detect if user trying to close window

查看:93
本文介绍了PySide/PyQt 检测用户是否尝试关闭窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检测用户是否试图关闭窗口?例如,在 Tkinter 中,我们可以这样做:

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()

谢谢.

推荐答案

覆盖 closeEvent 主窗口中 QWidget 的方法.

Override the closeEvent method of QWidget in your main window.

例如:

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

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

另一种可能是使用 QApplicationaboutToQuit 像这样的信号:

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

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

这篇关于PySide/PyQt 检测用户是否尝试关闭窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆