2

I have a GUI programmed in PyQt with many widgets and different windows, etc. The data for the GUI is stored in a python object. This object should be reachable from every widget in the program. Where should I put this object?

Right now I have it in the QMainWindow instance that is used for the program's main window. The problem is that it is hard to reach the QMainWindow object from deeply nested widgets. It seems much simpler to use the QApplication instance for that, because you can get it with QtCore.QCoreApplication.instance() (as shown in this answer). However, I couldn't find any other examples encouraging you to change the QApplication class, so I wonder if it really should be used that way.

What approach would you suggest?

4

1 回答 1

1

正确的方法是将此数据/设置对象放在单独的模块中。然后可以将其简单地导入任何需要的地方。理想情况下,模块(以及创建数据/设置对象的代码)应该在很大程度上独立于应用程序的其余部分。

将数据/设置对象绑定到应用程序实例并没有真正的价值,因为您仍然必须导入QApplicationqApp访问它。同样的事情也适用于QMainWindow- 它只是将问题移动到不同的位置,并添加了不必要的间接层。这种方法的另一个大问题是,在应用程序或主窗口的实例可用之前,无法访问数据/设置对象。很多时候,在应用程序的各个部分的初始化过程中都需要数据/设置对象,因此将其绑定到特定的 GUI 元素很容易导致循环依赖或其他排序问题。

我想这里的关键设计原则是松散耦合:一旦您将数据/设置对象与 GUI 分离,应用程序的其余部分就可以随时随地访问它。

于 2017-12-07T18:13:06.177 回答