1

I am writing a Python thing and I need the code to wait for the Qt to finish before continuing.

import sys
from PyQt5 import QtWidgets, QtGui, QtCore

class Test():
    def __init__(self):
        self.open_qt()

    def open_qt(self):
        app = QtWidgets.QApplication(sys.argv)
        self.window = QtWidgets.QWidget() # I tried QDialog also

        btn = QtWidgets.QPushButton("press me")
        btn.clicked.connect(self.login)

        lay = QtWidgets.QVBoxLayout()
        lay.addWidget(btn)

        self.window.setLayout(lay)
        self.window.show()

        sys.exit(app.exec_())

    def login(self):
        print("logged in!")

print("before")
temp = Test()
print("after")

This prints as:

before
after
logged in!

or:

before
logged in!
(after never arrives even after closing the Qt window)

But I need it to be:

before
logged in!
after
Frank
  • 2,109
  • 7
  • 25
  • 48
  • That's interesting. The way it works on my PC is `before` then `logged in!`. But even after I close the app I don't get the `after` print. – Jakub Szlaur Feb 15 '21 at 09:12
  • 1
    I actually had this as well. I added it to the examples. – Frank Feb 15 '21 at 09:17
  • So you want to print the `after` statement after the GUI is closed right (I am not sure on the *I need the code to wait for the Qt to finish before continuing*)? – Jakub Szlaur Feb 15 '21 at 09:18

1 Answers1

1

Okey so the problem in your case was with the sys.exit(app.exec_()) at the end of the open_qt(self) method:

  • This line of code sys.exit(app.exec_()) means that after app closes (executes), you will also immediately call the sys.exit() function.
  • sys.exit() then immediately terminates the script so your code doesn't get to the print("after") statement.
  • Rewrite this part to just simply: app.exec_()
  • Then you will see the after statement print out without any problem after you close the GUI.
Jakub Szlaur
  • 1,852
  • 10
  • 39
  • Thanks this solved the question correctly. But I have an added problem on this. I actually run this code in Maya. So I don't use the lines `app = QtWidgets.QApplication(sys.argv)` and `app.exec_()`. So how can I make the code wait in another app like Maya? – Frank Feb 15 '21 at 09:34
  • Sorry I don't know anything about `Maya`. You can maybe start a follow up question for this? – Jakub Szlaur Feb 15 '21 at 09:42
  • 1
    Ok thanks for your help though! Here is the other ticket for anyone that has this problem as well https://stackoverflow.com/questions/66205937/maya-wait-for-qt-window-to-close – Frank Feb 15 '21 at 09:59