首页 > 解决方案 > 项目结构设计:工具栏图标存储在哪里以及如何访问它们

问题描述

我正在开发一个包含一组图标图像的 GUI 项目。我本能地img在根项目目录中创建了一个目录。

我正计划使用我的应用程序的根类作为存储此类内容的地方,并将QIcon对象收集在字典中

self.toolbarIcons = {QIcon("<path-to-image.png>")}

那么问题是如何最好地从层次结构中的几个类访问这些图标。当我使用tkinter该结构时,结构非常线性,因为每个小部件都是其父级的子级。

我设置Qt应用程序的方式(使用PySide6),基类是QApplication. 在这里,我构造了一个QMainWindow,在其中设置了各种小部件(中央小部件、工具栏、状态栏等)。

随着应用程序复杂性的增长,有什么好的策略可以很好地扩展?我是否应该将与特定小部件相关的图标存储为该特定类的类属性(并因此在整个代码中传播图标对象)?我喜欢将图标对象放在一个位置的想法。

我将代码分隔在不同的目录中,但基本上结构是这样的(MWE):

from PySide6.QtWidgets import QApplication, QMainWindow, QTableWidget, QToolBar
from PySide6.QtGui import QIcon


class MyApplication(QApplication):
    def __init__(self, *args, **kwargs):
        QApplication.__init__(self, *args, **kwargs)
        
        self.icons = {'do_stuff': QIcon('<path-to-icon.png>')}
        self.mainwindow = MyMainWindow()
        self.mainwindow.show()


class MyMainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)

        self.setCentralWidget(MyCentralWidget(self))
        self.addToolBar(MyToolBar(self))


class MyCentralWidget(QTableWidget):
    def __init__(self, parent, *args, **kwargs):
        QTableWidget.__init__(self, parent, *args, **kwargs)
        self.parent = parent


class MyToolBar(QToolBar):
    def __init__(self, parent, *args, **kwargs):
        QToolBar.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        # How to access MyApplication.icons['do_stuff'] from here?


if __name__ == '__main__':
    app = MyApplication()
    app.exec_()


标签: pythonqtpyside6

解决方案


最简单的解决方案是 QApplication 是一个单例,可以使用 instance() 方法在任何方法中访问:

icon = MyApplication.instance().icons["do_stuff"]

但我不推荐它,因为更好的选择是创建一个定义这些属性的设置文件并将其导入:

设置.py

ICONS = {"do_stuff": "<path-to-icon.png>"}

然后

* .py

from settings import ICONS

# ...

icon = QIcon(ICONS["do_stuff"])

推荐阅读