Really strange behavior

David Boddie david at boddie.org.uk
Mon Nov 6 11:58:57 EST 2006


Sion Arrowsmith wrote:

> I don't know if this is the problem or not (knowing neither Qt nor
> Twisted), but creWin() creates a window (or two) then throws it
> (them?) away on returning to main() (I assume you've chopped
> off the bit where main() is actually called). So it's not too
> surprising your window doesn't show: by the time you get to
> running anything, you don't have a window object to show.

It seems to me that your analysis is correct. The first example
works as expected because MainWindow is still in scope when
the reactor is run.

def main():
     app = QtGui.QApplication(sys.argv)
     qt4reactor.install(app)
     MainWindow = QtGui.QMainWindow()
     win = Window(MainWindow)
     MainWindow.show()
     from twisted.internet import reactor
     reactor.run()

However, in the second example, MainWindow is created as a local
variable inside creWin() and is deleted when that function returns.

def creWin():
     MainWindow = QtGui.QMainWindow()
     win = Window(MainWindow)
     MainWindow.show()
 def main():
     app = creApp()
     creWin()
     from twisted.internet import reactor
     reactor.run()

By the time the reactor runs, there's no window (open or otherwise)
so the application will never exit the Qt event loop (or whatever
actually runs when Twisted is involved).

> (Unless a Qt application object is a discoverable global and
> windows inject a reference to themselves into it.)

Well, you can access the application's instance, once it's been set
up, via the qApp global variable in the PyQt4.QtGui module. However,
you can't take advantage of Qt's parent-based object ownership
mechanism to get round this issue with local variables because
widgets need to be given QWidget parents, and QApplication is not a
QWidget subclass.

The original poster should either use a global MainWindow variable or
encapsulate the functions in a class.

David




More information about the Python-list mailing list