Pyqt检查其他窗口何时关闭

Posted

技术标签:

【中文标题】Pyqt检查其他窗口何时关闭【英文标题】:Pyqt check when other window is closed 【发布时间】:2017-06-29 19:43:26 【问题描述】:

假设我有 2 个窗口,其中一个在单击菜单项时打开另一个窗口:

class ProjectWindow(QtWidgets.QMainWindow, project_window_qt.Ui_ProjectWindow):
    def __init__(self):
        super(ProjectWindow, self).__init__()

        # Setup the main window UI
        self.setupUi(self)
        self.new_project_window = None

        # Handle menu bar item click events
        self.actionNewProject.triggered.connect(self.new_project)

    def new_project(self):
        self.new_project_window = project_new_window.NewProjectWindow()
        self.new_project_window.show()

    def refresh_projects(self):
        with open(os.path.join(self.directory, 'projects.txt'), 'r') as f:
            projects = json.load(f)

        return projects

class NewProjectWindow(QtWidgets.QDialog, project_new_window_qt.Ui_NewProjectWindow):
    def __init__(self,):
        super(NewProjectWindow, self).__init__()

        # Setup the main window UI
        self.setupUi(self)

一旦用户关闭new_project_window,我希望在ProjectWindow 类中调用refresh_projects 方法。

我想过设置一个事件监听器来检查new_project_window何时关闭,然后在发生这种情况时调用refresh_projects,但窗口在打开后立即关闭:

def new_project(self):
    self.new_project_window = project_new_window.NewProjectWindow(self.directory, self.project_list)
    self.new_project_window.onClose.connect(self.refresh_projects)
    self.new_project_window.show()

这是正确的方法吗?或者有没有办法直接从new_project_window 对象中调用refresh_projects

【问题讨论】:

什么是 onClose? 【参考方案1】:

如果你使用QDialog,你应该调用exec_()而不是show(),这将在用户关闭窗口时返回一个值,然后调用刷新项目。

def new_project(self):
    self.new_project_window = project_new_window.NewProjectWindow(self.directory, self.project_list)
    code = self.new_project_window.exec_()
    """code: gets the value of the QDialog.Accepted, or QDialog.Rejected 
    that you can connect it to some accept button
    using the accept() and reject() functions.
    """
    self.refresh_projects()

exec_() 处于阻塞状态,即除非QDialog 已关闭,否则不会执行下一行。

【讨论】:

以上是关于Pyqt检查其他窗口何时关闭的主要内容,如果未能解决你的问题,请参考以下文章

javascript 检查浏览器窗口何时关闭

关闭窗口时如何触发pyqt5信号[重复]

PyQt - 如何在不关闭对话框窗口的情况下停止执行

如何关闭登录对话框并显示主窗口(PyQt4)[重复]

pyqt中QMdiArea子窗口关闭的问题

PyQt5从子窗口关闭父窗口和子窗口