How do I properly subclass QApplication?

I am new to PyQt4 (and QT in general) and am facing a problem,

I have subclasses of QApplication (to have global data and functions that are truly global to the application):

class App(QApplication): def __init__(self): QApplication.__init__(self) self.foo = None def bar(self,x): do_something() 

When I try to add a slot to my main window, for example:

self.connect(bar, SIGNAL('triggered()'), qApp.bar)

I get an error: AttributeError: bar

What am I doing wrong? Or should I make the material I want global, global stuff instead of the attributes and methods of the QApplication subclass? (or something else, if so, then what?)

Note: all this worked perfectly when the "global" methods and attributes were in my QMainWindow class ...

+4
source share
2 answers

Try adding QtGui.qApp = self to your __init__ method (or try using QApplication.instance() instead of qApp ).

I hope this helps.

+3
source

Object Oriented Approach:

 from PySide.QtCore import * from PySide.QtGui import * import sys ....import your classes ... ''' classes needing 'global' application attributes use for example: QCoreApplication.instance().mainWindow ''' class MyApp(QApplication): def __init__(self, args): super(MyApp, self).__init__(args) self.mainWindow = MainWindow() # 'global' ... self.exec_() # enter event loop app = MyApp(sys.argv) # instantiate app object 

As discussed in Bertrand Meyer "Object Oriented Software Construction", the OO program instantiates a single object β€” the application object. Using the main() routine is a relic of C-style procedural programming.

In addition, the following code may crash: In other words, MyApp.__init__() should go into the main event loop, not main() .

 ... def main(args): app = MyApp(args) ... sys.exit(app.exec_()) # Qt event loop if __name__ == "__main__": main(sys.argv) 

Other examples: http://en.wikibooks.org/wiki/Python_Programming/PyQt4

+1
source

All Articles