PyQt:系统任务栏应用程序中的“显示"菜单 [英] PyQt: Show menu in a system tray application

查看:201
本文介绍了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.

推荐答案

好吧,经过一些调试后,我发现了问题所在.完成__init__函数后销毁的QMenu对象,因为它没有父对象.虽然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天全站免登陆