QSystemTrayIcon 上下文菜单在子类化时不显示



我在windows 10上运行python 3.9.7。请考虑以下代码(注意,您需要icon.png才能运行(

from PyQt6.QtGui import QAction, QIcon
from PyQt6.QtWidgets import QSystemTrayIcon, QApplication, QMenu


app = QApplication([])
app.setQuitOnLastWindowClosed(False)
'''Create the system tray'''
tray = QSystemTrayIcon()
tray.setIcon(QIcon("icon.png"))
tray.show()

'''Add a menu with a quit action'''
menu = QMenu()
quit = QAction("Quit")
quit.triggered.connect(app.quit)
menu.addAction(quit)
'''Give the menu to the tray'''
tray.setContextMenu(menu)
'''Lets see where the menu is drawn'''
menu.aboutToShow.connect(lambda: print(menu.pos()))

app.exec()

以上内容在我的系统中按预期运行。然而,当我将QSystemTrayIcon子类化为这样时:

from PyQt6.QtGui import QAction, QIcon
from PyQt6.QtWidgets import QSystemTrayIcon, QApplication, QMenu
class SystemTrayIcon(QSystemTrayIcon):

def __init__(self, icon: QIcon, app: QApplication, *args, **kwargs):
super().__init__(*args, **kwargs)

'''setup'''
self.setIcon(icon)
self.show()

'''Add a menu with a quit action'''
menu = QMenu()
quit = QAction("Quit")
quit.triggered.connect(app.quit)
menu.addAction(quit)
'''Give the menu to the tray'''
self.setContextMenu(menu)

'''Lets see where the menu is drawn'''
menu.aboutToShow.connect(lambda: print(menu.pos()))


def main():
'''Define app'''
app = QApplication([])
app.setQuitOnLastWindowClosed(False)

'''System tray'''
tray_icon = SystemTrayIcon(QIcon('icon.png'), app)
app.exec()

if __name__ == '__main__':
main()

菜单不显示。lambda打印位置很有趣,在我的屏幕上,第一个代码返回类似于:PyQt6.QtCore.QPoint(1686, 1036),而第二个代码返回PyQt6.QtCore.QPoint(1686, 1064),大约低30个像素。我的屏幕分辨率是1080p,所以它不是在屏幕外,但确实表明了一些不同的行为。你知道为什么第二个例子中没有显示菜单吗?

需要保留对QAction的引用。这项工作:

from PyQt6.QtGui import QAction, QIcon
from PyQt6.QtWidgets import QSystemTrayIcon, QApplication, QMenu
class SystemTrayIcon(QSystemTrayIcon):

def __init__(self, icon: QIcon, app: QApplication, *args, **kwargs):
super().__init__(*args, **kwargs)

'''setup'''
self.setIcon(icon)
self.show()

'''Add a menu with a quit action'''
menu = QMenu()
self.quit = QAction("Quit")
self.quit.triggered.connect(app.quit)
menu.addAction(self.quit)
'''Give the menu to the tray'''
self.setContextMenu(menu)

'''Lets see where the menu is drawn'''
menu.aboutToShow.connect(lambda: print(menu.pos()))


def main():
'''Define app'''
app = QApplication([])
app.setQuitOnLastWindowClosed(False)

'''System tray'''
tray_icon = SystemTrayIcon(QIcon('icon.png'), app)
app.exec()

if __name__ == '__main__':
main()

相关内容

  • 没有找到相关文章

最新更新