PePeTD
PePeTD

Reputation: 158

PyQt window closes immediately after opening

I am getting an issue when trying to open a PyQt window.

The code below is an example of my original code. When I imported the module in import Test and ran test.Start(), I got the following error:

QCoreApplication::exec: The event loop is already running

After some research, I found out it was because I had already already made a QApplication.

test.py....
import sys

def Start():
    app = QApplication(sys.argv)
    m = myWindow()
    m.show()
    app.exec_()

class myWindow():....

if __name__ == "__main__":
    Start()

So then I read that I could rewrite my code like this and it would fix the error:

test.py....

def Start():
    m = myWindow()
    m.show()


class myWindow():....

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    Start()
    app.exec_()

Now I no longer get the QCoreApplication::exec: The event loop is already running error, but my window closes almost immediately after opening.

Upvotes: 13

Views: 26416

Answers (3)

Huseyin Sozen
Huseyin Sozen

Reputation: 9

Use the following code. Your problem is in your imports and using "show" as a name for function as far as I assume. You haven't provided what you have written in your class, so it's difficult to guess. But following code works like a charm. ;-)

Best wishes, good luck!

import sys
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

app = QApplication(sys.argv)
def Start():
    m = myWindow()
    m.showWid()
    sys.exit(app.exec())

class myWindow:
  def __init__(self):
    self.window = QWidget()
    self.window.setWindowTitle("Program Title")
    self.window.setFixedWidth(600)
    self.window.setStyleSheet("background: #18BEBE;")

  def showWid(self):
    self.window.show()

if __name__ == "__main__":
    Start()

Upvotes: 1

Josh
Josh

Reputation: 1052

You can also do:

def Start():
    global m
    m = myWindow()
    m.show()

class myWindow():....

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    window = Start()
    app.exec_()

Upvotes: 12

mata
mata

Reputation: 69012

You need to keep a reference to the opened window, otherwise it goes out of scope and is garbage collected, which will destroy the underlying C++ object also. Try:

def Start():
    m = myWindow()
    m.show()
    return m


class myWindow():....

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    window = Start()
    app.exec_()

Upvotes: 33

Related Questions