0

I have a UI file that I created using Qt Creator. When I execute the application through PyCharm, the main window opens briefly, then closes. I assume it is being garbage collected, but I'm not sure how to get this to work. Any ideas?

Calculator.py

from PyQt5.QtWidgets import QApplication
import MainWindow
import sys


class Calculator(QApplication):

    def __init__(self):
        args = sys.argv
        QApplication.__init__(self, args)
        self.initializeApplication()

    def initializeApplication(self):
        app = MainWindow.MainWindow()
        app.show()


if __name__ == '__main__':
    app = Calculator()
    sys.exit(app.exec_())

MainWindow.py

from PyQt5 import uic
from PyQt5.QtWidgets import QMainWindow


class MainWindow(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self, None)
        uic.loadUi(r'interface/MainWindow.ui', self)
        self.initializeUI()

    def initializeUI(self):
        self.setWindowTitle('Calculator')

I'm new to Python so please bear with me. I have looked at a few different examples, but nothing that really covers when your application spans multiple source files. Thanks.

artomason
  • 3,625
  • 5
  • 20
  • 43

1 Answers1

1

The comment that the garbage collector is deleting it is correct since the variables created in a function only exist while the function is called. Also to be able to execute a GUI, you must call exec_() to generate the main loop that is needed.

class Calculator(QApplication):

    def __init__(self):
        args = sys.argv
        QApplication.__init__(self, args)
        self.initializeApplication()
        self.exec_()

    def initializeApplication(self):
        self.app = MainWindow.MainWindow()
        self.app.show()


if __name__ == '__main__':
    app = Calculator()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • That seems to work perfectly, thank you! Is there a cleaner way to accomplish this. Everything I have read, and the examples I have looked at seem to go about this different ways. – artomason Nov 19 '17 at 22:40
  • This method I see adequate. Do not forget to mark my answer as correct. – eyllanesc Nov 19 '17 at 22:41