Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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_()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...