4

Build a menubar macos App using PyQt5 and PyInstaller

 1 year ago
source link: https://www.chunyangwen.com/blog/python/build-a-menubar-app-for-mac-with-qt.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

PyQt code

from PyQt5.QtWidgets import (
    QApplication,
    QSystemTrayIcon,
    QMainWindow,
    QTextEdit,
    QMenu,
    QAction,
)
from PyQt5.QtGui import QIcon
from PyQt5 import QtCore
import sys
import os

app = QApplication(sys.argv)

# Close window without exiting the application
app.setQuitOnLastWindowClosed(False)

# Create the icon
path = os.path.dirname(__file__)
icon = QIcon(os.path.join(path, "animal-penguin.png"))
# Create the tray
tray = QSystemTrayIcon()
tray.setIcon(icon)

tray.setVisible(True)

menu = QMenu()
quit = QAction("Quit")
quit.triggered.connect(app.quit)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        menu = self.menuBar()
        file_menu = menu.addMenu("&File")
        self.quit = QAction("&Quit")
        self.quit.triggered.connect(app.quit)
        file_menu.addAction(self.quit)
        self.editor = QTextEdit(self)
        self.load()  # Load up the text from file.

        self.setCentralWidget(self.editor)
        self.setWindowTitle("PenguinNotes")

    def load(self):
        if os.path.exists("notes.txt"):
            with open("notes.txt", "r") as f:
                text = f.read()
            self.editor.setPlainText(text)

    def save(self):
        text = self.editor.toPlainText()
        with open("notes.txt", "w") as f:
            f.write(text)

    def activate(self, reason):
        if reason == QSystemTrayIcon.Trigger:  # Icon clicked.
            self.show()

    def notes(self):
        self.show()
        self.setWindowState(QtCore.Qt.WindowState.WindowActive)
        self.raise_()

w = MainWindow()

notes_action = QAction("Notes")
menu.addAction(notes_action)
menu.addAction(quit)
notes_action.triggered.connect(w.notes)
tray.setContextMenu(menu)
# tray.activated.connect(w.activate)
app.aboutToQuit.connect(w.save)
app.setWindowIcon(QIcon("animal-penguin.png"))
app.exec()

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK