Python PyQt app.exec()似乎是非阻塞的
我有一个相当复杂的PyQt应用程序(Qt5,在Spyder中运行),最后我做了Python PyQt app.exec()似乎是非阻塞的,python,pyqt,spyder,Python,Pyqt,Spyder,我有一个相当复杂的PyQt应用程序(Qt5,在Spyder中运行),最后我做了 def main(): from PyQt5 import QtWidgets if not QtWidgets.QApplication.instance(): app = QtWidgets.QApplication(sys.argv) else: app = QtWidgets.QApplication.instance() main_windo
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()
(由于(第二个答案),需要进行if-else检查。)当我运行此代码时,我的应用程序会显示,同时打印状态代码
-1
(由于spyder/utils/ipython/start\u kernel.py
中引发的错误)。我的问题是,为什么会打印这个错误,因为我认为app.exec_u2;()是一个阻塞调用,并且直到该应用以某种方式退出后才会返回状态。这是因为Spyder运行自己的QApplication
?不可能多次执行应用程序事件循环。这很容易用一个简单的脚本进行测试:
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_())
输出:
QCoreApplication::exec: The event loop is already running
-1
因此,如果事件循环已经在运行,exec
只是立即返回而不阻塞
(注意:显然,您需要在普通控制台中运行上述脚本才能正确测试它)。如果在运行应用程序之前运行
%gui qt5
,会发生什么情况?您好,Carlos,我遵循了您关于我之前遇到的问题的建议,并将Ipython shell的设置更改为自动。即使我手动运行%gui qt5
,错误仍然存在(这是著名的keyrorm
,因为\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu?或者这更像是一个非问题?这完全有道理。非常感谢。