PyQt:在QMessageBox之后退出QSystemTrayIcon程序

PyQt: Exit QSystemTrayIcon program after QMessageBox

我有一个主要基于 QSystemTrayIcon 的简单脚本。发现一切正常,右键单击退出程序的任务栏图标有一个选项。我想添加一个QMessageBox,然后选择是,退出程序;否则,什么也不做。

我对这一切都很熟悉,但它不能正常工作,因此才有了这个问题。我创建了一个最小示例来演示该问题:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets


class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
    def __init__(self, icon, parent=None):
        QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
        self.menu = QtWidgets.QMenu(parent)
        self.exit_action = self.menu.addAction("Exit")
        self.setContextMenu(self.menu)
        self.exit_action.triggered.connect(self.slot_exit)

        self.msg_parent = QtWidgets.QWidget()

    def slot_exit(self):
        reply = QtWidgets.QMessageBox.question(self.msg_parent, "Confirm exit",
                                               "Are you sure you want to exit Persistent Launcher?",
                                               QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
        # if reply == QtWidgets.QMessageBox.Yes:
        #     QtCore.QCoreApplication.exit(0)


def main():
    app = QtWidgets.QApplication(sys.argv)

    tray_icon = SystemTrayIcon(QtGui.QIcon("TheIcon.png"))

    tray_icon.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

现在你看,在 slot_exit() 函数中,无论我选择是还是否,程序都会退出(代码为 0,没有错误)。注释部分是我期望用于根据选择确定动作的部分。你能帮我弄清楚为什么会发生这种行为,以及仅在 "yes" 时退出的正确方法是什么?

我正在使用 Windows 10、64 位、Python Anaconda 3.5.2 32 位和 PyQt 5.7。

问题是当所有 Windows 关闭时,Qt 会退出。只需禁用它:

app.setQuitOnLastWindowClosed(False)

在你的 main().