我有一个小的非GUI应用程序,该应用程序基本上会启动事件循环,将信号连接到插槽,然后发出信号。我希望该插槽停止事件循环并退出应用程序。
但是,应用程序不会退出。
有人对如何退出事件循环有任何想法吗?
Python 3.7.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_())
答案 0 :(得分:0)
当您调用app.exec_()
时,您正在进入Qt事件循环,但是由于在对象初始化时正在执行调用quit()
的代码,因此您的应用程序将永远不会退出。
我可以想到两种方法来实现您要执行的“退出”过程:
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_())