python - 项目结构设计:工具栏图标存储在哪里以及如何访问它们
问题描述
我正在开发一个包含一组图标图像的 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_()
解决方案
最简单的解决方案是 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"])
推荐阅读
- excel - 如何在 Excel 中使用 VBA 放置焦点并单击提交按钮?
- android - StfalconImageViewer 跟踪正在查看的当前图像
- php - 使用 $_POST 从应用程序连接到服务器的一些问题
- python - 如何等待(不使用 await 关键字)asyncio 任务完成并检索结果?
- c++ - 通过指针为布尔数组分配动态内存的段错误?
- python - 从 tkinter 中的列表框小部件返回列表
- arm - 我想用拇指汇编语言实现 R10=R11+OxFFFFE
- python-3.x - 使用 XLRD 从 excel 表中的列中读取 int 值
- java - Debezium - 更新操作将更改事件发送到具有前后结构值的 Kafka 主题,但忽略结构前的空列/字段
- java - Vertx HttpServerRequest 中的语法