PyQt:在系统托盘应用程序中显示菜单 [英] PyQt: Show menu in a system tray application

查看:28
本文介绍了PyQt:在系统托盘应用程序中显示菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是一位经验丰富的 C 程序员,但对 Python 不熟悉.我想使用 pyqt 在 python 中创建一个简单的应用程序.让我们想象一下这个应用程序很简单,当它运行时,它必须在系统托盘中放置一个图标,并在其菜单中提供一个退出应用程序的选项.

First of all, I'm an experienced C programmer but new to python. I want to create a simple application in python using pyqt. Let's imagine this application it is as simple as when it is run it has to put an icon in the system tray and it has offer an option in its menu to exit the application.

此代码有效,它显示菜单(为了简单起见,我没有连接退出操作等)

This code works, it shows the menu (I don't connect the exit action and so on to keep it simple)

import sys
from PyQt4 import QtGui

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

    trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app)
    menu = QtGui.QMenu()
    exitAction = menu.addAction("Exit")
    trayIcon.setContextMenu(menu)

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

if __name__ == '__main__':
    main()

但这不会:

import sys
from PyQt4 import QtGui

class SystemTrayIcon(QtGui.QSystemTrayIcon):

    def __init__(self, icon, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, icon, parent)
        menu = QtGui.QMenu()
        exitAction = menu.addAction("Exit")
        self.setContextMenu(menu)

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

    trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), app)

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

if __name__ == '__main__':
    main()

我可能错过了一些东西.没有错误,但在第二种情况下,当我单击右键时,它不显示菜单.

I probably miss something. There are no errors but in the second case when I click with the right button it doesn't show the menu.

推荐答案

好吧,经过一些调试我发现了问题.QMenu 对象在完成 __init__ 函数后被销毁,因为它没有父级.虽然 QSystemTrayIcon 的父级可以是 QMenu 的对象,但它必须是 Qwidget.此代码有效(请参阅 QMenu 如何获得与作为 QWidget 的 QSystemTrayIcon 相同的父级):

Well, after some debugging I found the problem. The QMenu object it is destroyed after finish __init__ function because it doesn't have a parent. While the parent of a QSystemTrayIcon can be an object for the QMenu it has to be a Qwidget. This code works (see how QMenu gets the same parent as the QSystemTrayIcon which is an QWidget):

import sys
from PyQt4 import QtGui

class SystemTrayIcon(QtGui.QSystemTrayIcon):

    def __init__(self, icon, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, icon, parent)
        menu = QtGui.QMenu(parent)
        exitAction = menu.addAction("Exit")
        self.setContextMenu(menu)

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

    w = QtGui.QWidget()
    trayIcon = SystemTrayIcon(QtGui.QIcon("Bomb.xpm"), w)

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

if __name__ == '__main__':
    main()

这篇关于PyQt:在系统托盘应用程序中显示菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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