PySide6 exec()函数详细教程
PySide6.QtWidgets.Application
类的exec()
函数使程序进入Qt主事件循环并等待直到调用exit()
函数,然后返回调用exit()
时设置的值,如果调用的是quit()
函数,则是0;此处的exit()
和quit()
函数是QApplication
类的成员函数;
需要调用这个函数来启动事件处理;主事件循环从窗口系统接收事件并将这些事件分派给应用程序的小部件;
通常,在调用exec()
之前不能进行用户交互;但可以在调用exec()
之前使用像QMessageBox
这样的模态小部件;
示例代码
import sys
from PySide6.QtWidgets import QApplication,QWidget,QPushButton,QVBoxLayout
from PySide6.QtCore import Slot
class MyWidget(QWidget):
def __init__(self):
super().__init__()
self.button = QPushButton("退出")
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.button)
self.button.clicked.connect(self.exitFunc)
@Slot()
def exitFunc(self):
app.exit(1) # app.exec()将返回 1
#app.exit(2) #app.exec()将返回2
#app.quit() #app.exec()将返回 0
app = QApplication([])
widget = MyWidget()
widget.resize(300, 200)
widget.show()
exitCode = app.exec()
print("退出码为:",exitCode)
sys.exit(exitCode)