PyQt: Show menu in a system tray application

前端 未结 6 1112
后悔当初
后悔当初 2020-12-02 08:45

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

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 09:38

    I couldn't get any of the above answers to work in PyQt5 (the exit in the system tray menu, wouldn't actually exit), but i managed to combine them for a solution that does work. I'm still trying to determine if exitAction should be used further somehow.

    import sys
    from PyQt5 import QtWidgets, QtCore, QtGui
    
    class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
    
        def __init__(self, icon, parent=None):
            QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
            menu = QtWidgets.QMenu(parent)
            exitAction = menu.addAction("Exit")
            self.setContextMenu(menu)
            menu.triggered.connect(self.exit)
    
        def exit(self):
            QtCore.QCoreApplication.exit()
    
    def main(image):
        app = QtWidgets.QApplication(sys.argv)
        w = QtWidgets.QWidget()
        trayIcon = SystemTrayIcon(QtGui.QIcon(image), w)
        trayIcon.show()
        sys.exit(app.exec_())
    
    
    if __name__ == '__main__':
        on='icon.ico'
        main(on)
    

提交回复
热议问题