2

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.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
dave
  • 897
  • 1
  • 7
  • 20
  • http://stackoverflow.com/questions/6159543/pyqt-how-to-get-top-level-parent-from-the-given-widget does this answer the question? – M4rtini Jan 27 '14 at 18:10
  • @M4rtini No, that's quite unrelated. – Kuba hasn't forgotten Monica Jan 27 '14 at 18:19
  • @M4rtini, yes that was helpful compared to the many parent calls I was having to make. Kuba's solution is a little more direct in getting to the main application object where I wanted to store my application wide attributes. Many thanks to you both! – dave Jan 27 '14 at 18:28

1 Answers1

9

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.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
  • Thanks Kuba! This is indeed the most direct way to get to my QApplication instance. I can also get rid of the app attribute in my QMainWindow object. – dave Jan 27 '14 at 18:26