MacOS PyQt5 - 右键单击Dock中的图标,显示所有打开的窗口

0 人关注

这个标题几乎说明了一切。

我怎样才能让一个用PyQt5构建的应用程序具有类似于下面所示的窗口行为?理想情况下,所有打开的窗口都会被显示出来,并有一个前台窗口的指示灯。

FIJI应用图标右击。

PyQt5应用程序图标右击(在多个窗口打开的情况下)。

4 个评论
也许通过一个自定义的QMenu,然后用 setAsDockMenu() ?
@musicamante 谢谢你的建议。我会看看这个,并让你知道我的发现。
好吧......我又琢磨了一下,我想我已经很接近解决这个问题了。我已经在主要评论@musicamante中加入了更新的代码。非常感谢任何进一步的反馈!
@musicamante 我想我已经建立了一个相当不错的原型解决方案--我很想听到你的反馈!
python
pyqt5
Jacob Bumgarner
Jacob Bumgarner
发布于 2022-03-16
1 个回答
Jacob Bumgarner
Jacob Bumgarner
发布于 2022-03-18
已采纳
0 人赞同

好吧--这是我开发的一个粗略的解决方案。我仍然需要弄清楚如何在窗口项目被销毁后将其从Dock中移除,而且我想添加指示器来显示窗口是可见还是隐藏。不过这是个好的开始

谢谢@musicamante的 setAsDockMenu() 旗帜。

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QMainWindow,QWidget, QPushButton,
                             QMenu, QVBoxLayout, QAction)
import sys
import platform
def add_menu(mainWindow):
    if platform.system() == "Darwin":
        mainWindow.menuBar = MenuBar()
        mainWindow.centralWidget().layout().addWidget(mainWindow.menuBar)
class MenuBar(QMenu):
    """ Menu bar that displays the open windows on MacOS """
    menu_items = {}
    def __init__(self):
        super().__init__()
        self.setAsDockMenu()
        self.hide()
    def add_window(self, window, title):
        show_action = self.addAction(title)
        show.triggered.connect(window.showNormal)
        self.menu_items[title] = show_action
        return
    def remove_window(self, title):
        show_action = self.menu_items.pop[title]
        self.removeAction(show_action)
        return
class Window(QWidget):
    def __init__(self, title, windows, dockMenu):
        super().__init__()
        self.title = title
        self.windows = windows
        self.dockMenu = dockMenu
        self.setWindowTitle(title)
        self.show()
    def closeEvent(self, event):
        self.windows.pop(self.title)
        if platform.system() == "Darwin":
            self.dockMenu.remove_window(self.title)
        event.accept()
        self.destroy()
class MainWindow(QMainWindow):
    windows = {}
    def __init__(self):
        super().__init__()
        self.setCentralWidget(QWidget())
        c_widget = self.centralWidget()
        c_widget.setLayout(QVBoxLayout())
        # If using MacOS, create a menubar to view windows.
        add_menu(self)
        add_item = QPushButton("Add")
        add_item.clicked.connect(self.add_window)
        c_widget.layout().addWidget(add_item)
        print_window = QPushButton("Print Windows")
        print_window.clicked.connect(self.show_windows)
        c_widget.layout().addWidget(print_window)
        self.show()
    def add_window(self):
        title = str(len(self.windows.keys()))
        self.window = Window(title, self.windows, self.menuBar)
        self.windows[title] = self.window
        self.menuBar.add_window(self.window, title)
    def show_windows(self):
        print (self.windows.keys())
    def closeEvent(self, event):
        QApplication.closeAllWindows()
        event.accept()