Kimvais
Kimvais

Reputation: 39618

How do I subclass QApplication properly?

I am a newbie with PyQt4 (and QT altogether), and am facing a problem,

I have subclassed QApplication (to have global data and functions that really are 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 like:

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

I get an error: AttributeError: bar

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

Note: this all worked fine when the "global" methods and attributes were in my QMainWindow -subclass...

Upvotes: 7

Views: 4388

Answers (2)

bootchk
bootchk

Reputation: 2016

A pure object oriented approach is:

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's "Object Oriented Software Construction", a OO program instantiates one object, the application object. Using a main() procedure is a relict of C style procedural programming.

Also, the following code may crash: In other words, MyApp.__init__() should enter 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)

See other examples: http://en.wikibooks.org/wiki/Python_Programming/PyQt4

Upvotes: 4

Greg S
Greg S

Reputation: 12548

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

I hope that helps.

Upvotes: 3

Related Questions