事件循环是否将 运行 程序代码保留在 PyQt/PySide 中?

Does an event loop keep running the program's code in PyQt/PySide?

我知道在创建 QApplication 时,会创建一个事件循环。 这是否意味着应用程序将永远保留 运行ning 代码,直到它终止? 我试图在我的 Main class 构造函数中调用一个插槽,我想知道该插槽是否会继续执行,因为存在事件循环,因此 Main class 将永远实例化。 我怎么错了?为什么constructor方法运行只有一次?

事件循环只是一个无限循环,它从队列中取出事件并处理它们。

def exec_():
    while True:
        event = event_queue.get()
        process_event(event)

当您调用“exec_()”方法时,事件循环是运行。当您单击或与 GUI 交互时,您将事件放入事件队列。 Qt 在内部处理该事件。

您还会注意到长时间 运行ning 按钮单击会停止 GUI。一切都是 运行ning 同步进行的。单击按钮时,正在处理该事件。在该事件 运行ning 期间没有处理其他事件。

import time
from PySide2 import QtWidgets

app = QtWidgets.QApplication([])

def halt_10_sec():
    time.sleep(10)  # Stay here for 10 seconds

btn = QtWidgets.QPushButton('Halt')
btn.clicked.connect(halt_10_sec)
btn.show()

app.exec_()  # Run forever until app.quit()

# You will not get here until all windows are closed and the application is exiting.
print('Here')

单击按钮后,您将无法调整 window 的大小、移动 window、在悬停时突出显示按钮,或按钮事件为 [=24] 时的任何其他事件=]宁.

插槽只是一个函数。您应该能够在构造函数中调用插槽。