[英]Qt for Python QCoreApplication: How to Exit non-GUI application
I have a small non-GUI application that basically starts an event loop, connects a signal to a slot, and emits a signal. 我有一个小型的非GUI应用程序,该应用程序基本上会启动事件循环,将信号连接到插槽,然后发出信号。 I would like the slot to stop the event loop and exit the application.
我希望该插槽停止事件循环并退出应用程序。
However, the application does not exit. 但是,该应用程序不会退出。
Does anyone have any ideas on how to exit from the event loop? 是否有人对如何退出事件循环有任何想法?
Python 3.7.0 的Python 3.7.0
Qt for Python (PySide2) 5.12.0 适用于Python的Qt(PySide2)5.12.0
import sys
from PySide2 import QtCore, QtWidgets
class ConsoleTest(QtCore.QObject):
all_work_done = QtCore.Signal(str)
def __init__(self, parent=None):
super(ConsoleTest, self).__init__(parent)
self.run_test()
def run_test(self):
self.all_work_done.connect(self.stop_test)
self.all_work_done.emit("foo!")
@QtCore.Slot(str)
def stop_test(self, msg):
print(f"Test is being stopped, message: {msg}")
# neither of the next two lines will exit the application.
QtCore.QCoreApplication.quit()
# QtCore.QCoreApplication.exit(0)
return
if __name__ == "__main__":
app = QtCore.QCoreApplication(sys.argv)
mainwindow = ConsoleTest()
sys.exit(app.exec_())
When you call app.exec_()
you are entering the Qt event loop, but since you are executing the code that call quit()
at the moment the object is being initialized, your application will never quit. 当您调用
app.exec_()
您将进入Qt事件循环,但是由于您正在执行初始化对象时调用quit()
的代码,因此您的应用程序将永远不会退出。
I can think of two options to achieve the "exit" process you want to do: 我可以想到两种选择来实现您要执行的“退出”过程:
sys.exit(1)
inside the stop_test()
instead of a quit
or exit
call, or stop_test()
调用sys.exit(1)
stop_test()
而不是quit
或exit
调用,或者 import sys
from PySide2 import QtCore, QtWidgets
class ConsoleTest(QtCore.QObject):
all_work_done = QtCore.Signal(str)
def __init__(self, parent=None):
super(ConsoleTest, self).__init__(parent)
self.run_test()
def run_test(self):
self.all_work_done.connect(self.stop_test)
self.all_work_done.emit("foo!")
@QtCore.Slot(str)
def stop_test(self, msg):
print(f"Test is being stopped, message: {msg}")
QtCore.QTimer.singleShot(10, QtCore.qApp.quit)
if __name__ == "__main__":
app = QtCore.QCoreApplication(sys.argv)
mainwindow = ConsoleTest()
sys.exit(app.exec_())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.