PySide PyQt MainWindow or Central Widget access from deeply nested widgets

我只是一个虾纸丫 提交于 2019-12-24 11:36:36

问题


Calling out to PyQt gurus for some best practices.

I have some application universal attributes that I define as attributes on my QApplication. In my MainWindow initialization I assign an "app" attribute to the MainWindow. I would like to access the app's variables in deeply nested widgets. Right now, I can do so by calling enough "parent()" calls to get up to the level of MainWindow.

This seems kludgey and my guess is there is another solution that is best practice in this situation. Here are some snippets of code to better understand the issue.

Application Class

class App(QtGui.QApplication):

    def __init__(self, sim, *args, **kwargs):
        super(App, self).__init__(*args, **kwargs)
        self.sim = sim
        window = MW.BaseUI(digi_thread, app=self)

Main window class

class BaseUI(QtGui.QMainWindow):
    def __init__(self, digi_thread, app, parent=None):
        super(BaseUI, self).__init__(parent)
        self.app = app

An example of some code to get up to Main Window from a nested widget (a tab within a tabbook)

@property
def main_window(self):
    return self.parent().parent().parent().parent()

def some_function(self):
    if self.main_window.app.sim:
        print "in simulation mode"

I'm also not sure if the centralWidget has anything to do with solving this type of issue.


回答1:


You can always get to the current application instance via PySide.QtCore.QCoreApplication.instance(). In C++, the global qApp variable provides the same functionality.

So, whether you set python attributes, or Qt properties, on the global application instance, you can always get to it without having to go through any hierarchies.



来源:https://stackoverflow.com/questions/21388250/pyside-pyqt-mainwindow-or-central-widget-access-from-deeply-nested-widgets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!