2

I have a quite complicated PyQt app (Qt5, running in Spyder), where at the end I do

def main():
    from PyQt5 import QtWidgets
    if not QtWidgets.QApplication.instance():
        app = QtWidgets.QApplication(sys.argv)
    else:
        app = QtWidgets.QApplication.instance() 
    main_window = MainWindow()
    main_window.show()
    status = app.exec_()
    print status
    sys.exit(0)

if __name__ == "__main__":
    main()

(The if-else check is needed because of this(second answer).) When I run this code, my app shows, and the status code -1 is printed at the same time (due to a raised error in spyder/utils/ipython/start_kernel.py). My question is, why this error is printed at all, because I thougt that app.exec_() is a blocking call and the status is not returned until the app is exited somehow. Is this due to Spyder running its own QApplication?

Dschoni
  • 3,714
  • 6
  • 45
  • 80
  • What happens if you run `%gui qt5` before running your application? – Carlos Cordoba Oct 11 '17 at 15:28
  • Hi Carlos, I followed your advice regarding the issue I had before and changed the setting of the Ipython shell to automatic. Even if I run `%gui qt5` manually, the error remains (it's the famous `KeyError`, because `__file__` is not in `locals()`) – Dschoni Oct 11 '17 at 15:31
  • @CarlosCordoba is there already an open issue, regarding the underlying error? Or is this more like a non-issue? – Dschoni Oct 12 '17 at 09:49

1 Answers1

1

It is not possible to execute the application event-loop more than once. This is easy enough to test with a simple script:

import sys
from PyQt5 import QtCore, QtWidgets

app = QtWidgets.QApplication(sys.argv)
btn = QtWidgets.QPushButton('Test')
btn.clicked.connect(lambda: print(QtWidgets.QApplication.exec_()))
btn.show()
sys.exit(app.exec_())

Output:

QCoreApplication::exec: The event loop is already running
-1

So, if the event-loop is already running, exec just returns immediately without blocking.

(NB: obviously you will need to run the above script in a normal console to test it properly).

ekhumoro
  • 115,249
  • 20
  • 229
  • 336