PyQt:在 QMessageBox 之后退出 QSystemTrayIcon 程序 [英] PyQt: Exit QSystemTrayIcon program after QMessageBox

查看:74
本文介绍了PyQt:在 QMessageBox 之后退出 QSystemTrayIcon 程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主要基于 QSystemTrayIcon 的简单脚本.一切正常,找到,右键单击退出程序的任务栏图标有一个选项.我想添加一个QMessageBox,选择yes,退出程序;否则,什么都不做.

I have a simple script primarily based on QSystemTrayIcon. Everything works find, and there's an option there on right-click on the taskbar icon that exits the program. I would like to add a QMessageBox, and on choosing yes, exit the program; otherwise, do nothing.

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

I'm familiar with all that, but it doesn't work as it should, and hence the question. I created a minimal example to demonstrate the problem:

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() 函数中,无论我选择 yes 还是 no,程序都会退出(代码为 0,没有错误).注释部分是我期望用于根据选择确定操作的部分.能否请您帮我弄清楚为什么会发生这种行为,以及仅在是"时退出的正确方法是什么?

Now you see, at the slot_exit() function, whether I choose yes or no, the program exits (with code 0, no errors). The commented part is what I expect to be used to determine the action based on the choice. Could you please help me figure out why this behavior is happening and what's the right way to exit only on "yes"?

我使用的是带有 Python Anaconda 3.5.2 32 位和 PyQt 5.7 的 64 位 Windows 10.

I'm using Windows 10, 64-bit with Python Anaconda 3.5.2 32-bit, and PyQt 5.7.

推荐答案

问题是当所有 Windows 都关闭时,使 Qt 退出.只需使用以下命令禁用它:

The problem is that Qt is made to exit when all Windows are closed. Simply disable that with:

app.setQuitOnLastWindowClosed(False)

在你的main()中.

这篇关于PyQt:在 QMessageBox 之后退出 QSystemTrayIcon 程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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