事件循环是否会继续在PyQt / PySide中运行程序的代码?

问题描述

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

解决方法

事件循环只是一个无限循环,它将事件从队列中拉出并进行处理。

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

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

您还将注意到,长时间单击按钮将停止GUI。一切都在同步运行。单击按钮后,该事件正在处理中。该事件正在运行时,不会处理其他事件。

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')

单击按钮后,将无法调整窗口的大小,移动窗口,在悬停时突出显示按钮或按钮事件运行时的任何其他事件。

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...