Menubar/ System tray app with Qt

2020-05-29 07:09发布

问题:

I am new in Qt (PyQt) and I am trying to make an app whose functions will be executed from menubars/system trays. A perfect example is show here:

I cannot find a good resource on how I can do this. Can someone advice.

Thanks.

回答1:

I think you are looking for working with QMenu and QMainWindow for the menu part, at least.

Here you can find a C++ example:

Menus Example

and here a PyQt4 example:

Menus and Toolbars in PyQt4

Here is the code inline for your convenience:

import sys
from PyQt4 import QtGui

class Example(QtGui.QMainWindow):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):               

        exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self)        
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(QtGui.qApp.quit)

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Menubar')    
        self.show()


def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

As for the QSystemTrayIcon part, you could write something like this:

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

    w = QtGui.QWidget()
    trayIcon = QtGui.QSystemTrayIcon(QtGui.QIcon("Bomb.xpm"), w)
    menu = QtGui.QMenu(parent)
    exitAction = menu.addAction("Foo")
    trayIcon.setContextMenu(menu)

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

if __name__ == '__main__':
    main()