I'm learning to use the pyqt libraries and this code won't work (no output):

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from pomocni import Ui_MainWindow
from PyQt4.QtGui import QMainWindow, QApplication
from PyQt4 import QtCore
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

def start():
    window = MainWindow()
    window.show()
if __name__ == "__main__":
    app = QApplication(sys.argv)
    start()
    sys.exit(app.exec_())

Doing it this way, and everything is OK:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from pomocni import Ui_MainWindow
from PyQt4.QtGui import QMainWindow, QApplication
from PyQt4 import QtCore
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

What am I doing wrong?

Edited 3 Years Ago by zspoja: cleanup

In the first version, window is a local variable in function start(). It is probably garbage collected when the function exits. You need to keep a pointer to window.

OK. Thanks but the above code is a module and will be called from other pyqt programs on various events. The main function is there only for debuging purposes. So the module code is:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from pomocni import Ui_MainWindow
from PyQt4.QtGui import QMainWindow, QApplication
from PyQt4 import QtCore
import sys
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
def start():
    window = MainWindow()
    window.show()

and this code snippet:

import above_module
above_module.start()

does not work and I can't use a pointer because app.exec_() can not be called multiple times.

The most flexible solution is that the calling code stores the pointer to the window

def start():
    window = MainWindow()
    window.show()
    return window

# in calling code
import above_module
window = above_module.start()

The other solution is that the pointer is stored in above_module. For example

window = None

def start():
    global window
    window = MainWindow()
    window.show()

One drawback of this approach is that window is not automatically garbage collected, and if you want several instances, you'll have to use a container.

This question has already been answered. Start a new discussion instead.